Step 2 of 13
val vs var, type inference, string templates, nullable types, safe calls and Elvis operator
val vs var, ประเภทข้อมูล, string templates และ null safety ซึ่งเป็นฟีเจอร์สำคัญที่ทำให้ Kotlin ต่างจาก Java
Kotlin has two ways to declare variables:
val name = "Alice" // read-only (like Java's final)
var score = 0 // mutable (can reassign)
Use val by default. Only use var when you need to change the value later.
Kotlin has these built-in types:
val text: String = "Hello"
val count: Int = 42
val price: Double = 9.99
val flag: Boolean = true
val letter: Char = 'A'
You usually do not need to write the type. Kotlin infers it from the value:
val text = "Hello" // String
val count = 42 // Int
val price = 9.99 // Double
Insert variables and expressions inside strings:
val name = "Alice"
val age = 30
println("Name: $name") // Name: Alice
println("Next year: ${age + 1}") // Next year: 31
println("Length: ${name.length}") // Length: 5
This is Kotlin's most important feature. Types are non-nullable by default.
val name: String = "Alice"
// name = null // Compilation error!
val nullableName: String? = null // The ? makes it nullable
| Operator | Name | What it does |
|---|---|---|
?. | Safe call | Calls method if not null, returns null otherwise |
?: | Elvis | Provides a fallback value if null |
!! | Not-null assertion | Throws NPE if null — avoid this |
val name: String? = getName()
// Safe call + Elvis
val length: Int = name?.length ?: 0
// Chaining safe calls
val city: String? = user?.address?.city
Use ?.let to run a block only when the value is not null:
val email: String? = getEmail()
email?.let {
println("Sending to $it")
sendVerification(it)
}
Kotlin does not auto-convert between number types. You must call the conversion function:
val intVal = 42
val longVal: Long = intVal.toLong() // explicit conversion
val doubleVal: Double = intVal.toDouble()
Null pointer exceptions cost billions in debugging time. Kotlin's type system prevents them at compile time. When you see String, you know it is never null. When you see String?, you must handle the null case. This makes your code safer without runtime overhead.