⚡ Kotlin Fundamentals
Kotlin Basics: Variables & Types
val vs var, type inference, null safety, and the Elvis operator.

Why Kotlin?

Kotlin is Google's preferred language for Android development. It's concise, null-safe, and fully interoperable with Java. Visual Studio 2026 supports Kotlin code through .NET MAUI's Android interop layer.

Variables

kotlin
// val = immutable (use by default)
val appName = "My App"     // type inferred: String
val maxRetries: Int = 3

// var = mutable
var counter = 0
counter++

// Nullable types — add ?
var username: String? = null
username = "Alice"
val len = username?.length ?: 0  // Elvis: 0 if null

Control Flow

kotlin
// when — Kotlin's powerful switch/match
val grade = 85
val letter = when {
    grade >= 90 -> "A"
    grade >= 80 -> "B"
    grade >= 70 -> "C"
    else       -> "F"
}

// Range loop
for (i in 1..10) println(i)
for (i in 10 downTo 1 step 2) println(i)

Null Safety

kotlin
fun greet(name: String?) {
    println(name?.uppercase())       // safe call
    name?.let { println("Hi $it!") } // let block if non-null
    println(name ?: "Guest")         // Elvis default
}

Key Takeaways

Use val for immutable values; var only when mutation is needed
Nullable types require ? suffix and safe-call operator ?.
when replaces switch and works as an expression — it returns a value
Kotlin's null safety eliminates NullPointerExceptions at compile time
Lesson 6 of 30Kotlin Fundamentals
← Previous Next Lesson →