Kotlin Course

Kotlin Variables and Data Types

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

val and var

Kotlin has two keywords for variable declaration: val (immutable, like Java's final) and var (mutable). Prefer val whenever possible.

val pi = 3.14159      // immutable — cannot reassign
var count = 0         // mutable — can reassign
count = 5             // OK
// pi = 3.14          // ❌ Error: val cannot be reassigned

Type Annotations

Kotlin infers types automatically, but you can be explicit:

val name: String = "Alice"
val age: Int = 25
val height: Double = 1.75
val isStudent: Boolean = true

// Type inference
val city = "London"    // String
val score = 100        // Int
val ratio = 0.85       // Double

Basic Data Types

val i: Int = 42
val l: Long = 10_000_000L
val d: Double = 3.14
val f: Float = 3.14f
val b: Boolean = true
val c: Char = 'A'
val s: String = "Kotlin"

String Templates

val name = "Alice"
val age = 25
println("My name is $name and I am $age years old.")
// Expression inside template:
println("Next year I will be ${age + 1}")

Nullable Types

var nonNull: String = "hello"    // cannot be null
var nullable: String? = null     // can be null

// Safe call operator
println(nullable?.length)        // null (no crash)
// Elvis operator
val len = nullable?.length ?: 0
println(len)                     // 0