Kotlin User Manual
Variables and Basic Types
Kotlin uses two keywords for variable declaration: var and val. var declares a mutable variable, similar to a regular variable in Java. val declares an immutable variable, similar to a final variable in Java. In Kotlin, preferring val is a best practice that makes code safer and easier to understand.
When declaring variables, you can explicitly specify the type or let the compiler infer the type:
val name: String = "Kotlin" val age = 10 // Compiler infers Int type var count = 0 // Mutable variable
Kotlin's basic types include: integers (Int, Long, Short, Byte), floating-point numbers (Double, Float), characters (Char), booleans (Boolean), and strings (String). Unlike Java, all basic types in Kotlin are objects with corresponding member methods.
Kotlin integers default to Int type. To represent larger numbers, use the Long suffix:
val longNumber = 100L // Long type
Kotlin strings are powerful and support string templates, allowing variables or expressions to be embedded directly in strings:
val name = "World" println("Hello, $name!") // Outputs: Hello, World! println("Length: ${name.length}") // Outputs: Length: 5
Collections
The Kotlin standard library provides rich collection types including List, Set, and Map. Each collection type has both immutable and mutable versions.
Immutable collections cannot be added to, removed from, or modified after creation:
val list = listOf(1, 2, 3, 4, 5) val set = setOf("a", "b", "c") val map = mapOf("key1" to 1, "key2" to 2)
Mutable collections allow element modifications:
val mutableList = mutableListOf(1, 2, 3) mutableList.add(4) mutableList.removeAt(0)
Kotlin collections provide rich functional operations like map, filter, and reduce:
val numbers = listOf(1, 2, 3, 4, 5) val doubled = numbers.map { it * 2 } // [2, 4, 6, 8, 10] val evens = numbers.filter { it % 2 == 0 } // [2, 4] val sum = numbers.reduce { acc, i -> acc + i } // 15
Control Flow
Kotlin's control flow includes conditional expressions, loops, and jump expressions.
The if expression in Kotlin returns a value and can be directly assigned to a variable:
val max = if (a > b) a else b
The when expression is Kotlin's powerful multi-branch matching tool that can match various conditions:
when (x) { 1 -> println("x is 1") 2 -> println("x is 2") in 3..10 -> println("x is between 3 and 10") else -> println("x is something else") }
Kotlin's loops include for loops and while loops. For loops can iterate over ranges, arrays, and collections:
for (i in 1..10) { println(i) }
for (item in list) { println(item) }
for (i in list.indices) { println("Index: $i, Value: ${list[i]}") }
Functions
Kotlin uses the fun keyword to declare functions. Functions can specify parameter types and return types:
fun greet(name: String): String { return "Hello, $name!" }
If the function body has only one expression, you can use the single-expression syntax:
fun greet(name: String) = "Hello, $name!"
Kotlin supports default arguments and named arguments, which greatly reduces the need for function overloading:
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"
greet("World") // Hello, World! greet("World", "Hi") // Hi, World! greet(name = "World", greeting = "Hi") // Hi, World!
Kotlin also supports variadic parameters using the vararg keyword:
fun sum(vararg numbers: Int): Int { return numbers.sum() }
sum(1, 2, 3, 4, 5) // 15
Classes and Objects
Kotlin class declarations are more concise than Java. By default, Kotlin classes are final and cannot be inherited. To make a class inheritable, use the open keyword:
open class Animal(val name: String) { open fun speak() = println("$name makes a sound") }
class Dog(name: String) : Animal(name) { override fun speak() = println("$name barks") }
Kotlin's constructors include primary and secondary constructors. The primary constructor is declared directly after the class name:
class Person(val name: String, val age: Int)
If you need to execute logic in the constructor, use an init block:
class Person(name: String, age: Int) { val name: String val age: Int
init {
this.name = name
this.age = age
require(age >= 0) { "Age cannot be negative" }
}
}
Kotlin's data classes automatically generate equals, hashCode, toString, and copy methods, making them perfect for classes that store data:
data class User(val name: String, val email: String)
val user1 = User("Alice", "[email protected]") val user2 = user1.copy(email = "[email protected]")
Null Safety
Null safety is one of Kotlin's most important features. In Kotlin, the type system distinguishes between nullable and non-nullable types, which fundamentally reduces NullPointerExceptions.
By default, types are non-nullable:
val name: String = "Kotlin" // Cannot be null val name: String = null // Compilation error
To allow a variable to be null, use nullable types (?):
val name: String? = null // Can be null
When accessing properties or methods of nullable types, use the safe call operator (?.) or the non-null assertion (!!):
val length = name?.length // Returns null if name is null val length = name!!.length // Throws exception if name is null
The Elvis operator (?:) provides a concise way to handle default values:
val length = name?.length ?: 0 // Returns 0 if name is null
Extension Functions and Properties
Kotlin allows adding new functions and properties to existing classes without inheriting or modifying the original class. These are called extension functions and extension properties.
Extension functions are declared by prefixing the function name with the class name being extended:
fun String.addExclamation() = this + "!"
"Hello".addExclamation() // "Hello!"
Extension properties can also add new properties to existing classes:
val String.wordCount: Int get() = this.split(" ").size
"Hello World".wordCount // 2
Higher-Order Functions and Lambdas
Higher-order functions are functions that take functions as parameters or return functions. Lambda expressions are the primary way to implement this feature.
Lambda expression syntax uses curly braces:
val sum = { a: Int, b: Int -> a + b } sum(1, 2) // 3
If a lambda is the last parameter of a function, it can be moved outside the parentheses:
list.filter { it > 0 }
In lambda expressions, it represents the implicit name for a single parameter. When there's only one parameter, you can omit the parameter declaration.
Coroutines
Coroutines are the core feature of asynchronous programming in Kotlin. Compared to threads, coroutines are much more lightweight and can run multiple coroutines in a single thread.
launch is a common way to start coroutines, which starts a new coroutine in the background:
GlobalScope.launch { val data = async { fetchData() } updateUI(data.await()) }
Suspend functions can only be called within coroutines:
suspend fun fetchData(): Data { return withContext(Dispatchers.IO) { // Perform time-consuming operation } }
Kotlin coroutines provide multiple dispatchers to control which thread coroutines run on: Dispatchers.Main for UI operations, Dispatchers.IO for I/O operations, and Dispatchers.Default for CPU-intensive tasks.
Sealed Classes and Enums
Sealed classes are restricted class hierarchies that limit the number of subclasses that can inherit from it. All subclasses must be declared in the same file. This is very useful when representing finite states or result types:
sealed class Result
The when expression can fully utilize sealed class features, with the compiler checking if all possible cases are handled:
fun handleResult(result: Result
Enums represent a finite set of constant values:
enum class Direction { NORTH, SOUTH, EAST, WEST }
Enums can have properties and methods:
enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF);
fun containsRed() = (rgb and 0xFF0000) != 0
}
Interfaces and Abstract Classes
Interfaces in Kotlin can contain default implementations, making them more flexible:
interface Clickable { fun click() fun showOff() = println("I'm clickable!") }
Classes can implement multiple interfaces:
class Button : Clickable, Focusable { override fun click() = println("Button clicked") override fun showOff() { super
Object Expressions and Declarations
Object expressions create instances of anonymous classes, similar to Java's anonymous inner classes:
window.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { // Handle click event } })
Object declarations create singletons:
object Config { val apiUrl = "https://api.example.com" val timeout = 30 }
Companion Objects
Each class can contain a companion object, similar to static members in Java:
class MyClass { companion object { const val TAG = "MyClass" fun create() = MyClass() } }
Companion object members can be accessed directly via the class name:
MyClass.TAG MyClass.create()
Type Checks and Conversions
The is operator is used for type checking, similar to Java's instanceof:
if (obj is String) { // In this branch, obj is automatically cast to String println(obj.length) }
Smart casts automatically convert types that have been checked. If the compiler can infer the variable's type in a specific branch, it automatically performs the conversion.
If smart casts don't apply, you can use explicit casting:
val str = obj as String
Safe type casting uses as?, which returns null when casting fails:
val str = obj as? String // Returns null if casting fails
