</>
Skip to content
Kotlin lessons (7/33)

Kotlin — Variables

val and var

fun main() {
    // val: immutable (like final in Java)
    val name = "Alice"
    val age: Int = 30

    // var: mutable
    var count = 0
    count = 5 // OK

    // Type inference
    val pi = 3.14        // Double
    val isActive = true  // Boolean
    val text = "hello"   // String
}

Nullable types

var name: String? = null  // Nullable
var age: Int = 25          // Non-null

// Safe access
println(name?.length) // null

// Default value
val length = name?.length ?: 0

// Non-null assertion
// println(name!!.length) // Throws NPE if null

Destructuring

data class Person(val name: String, val age: Int)

fun main() {
    val person = Person("Alice", 30)
    val (name, age) = person
    println("$name, $age")

    // With index
    val (n, a) = person.component1() to person.component2()
}

Type checking and casting

fun main() {
    val obj: Any = "hello"

    // Smart cast
    if (obj is String) {
        println(obj.length) // Smart cast to String
    }

    // Safe cast
    val str: String? = obj as? String
    println(str?.length)

    // when with type checking
    when (obj) {
        is Int -> println("Int: $obj")
        is String -> println("String: $obj")
        else -> println("Other")
    }
}

Best practices

  • Use val over var whenever possible
  • Use explicit types for public APIs
  • Avoid !! — prefer safe calls and Elvis operator
  • Use data classes for simple data holders

Mini Practice

Write Kotlin code that:

  1. Uses val and var with type inference
  2. Demonstrates nullable types and safe calls
  3. Uses destructuring with a data class
  4. Shows smart casting with is

Up Next

In the next lesson, you'll learn about Data Types — the full type system in Kotlin.

Related Topics

Frequently Asked Questions about Variables

What is Variables in Kotlin?

Variables is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Variables?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Variables.

Why is Variables important in Kotlin?

Variables is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.