Kotlin · Module 1 · Lesson 21 min read

Variables, Types & Strings

val vs var

kotlin
val name = "Asha"     // read-only, can't be reassigned (prefer this)
var score = 0         // mutable, can change
score += 10

Prefer val. Use var only when the value really changes. Code with fewer changing parts has fewer bugs.

Type inference

Kotlin works out the type, but you can write it: val age: Int = 20.

Basic types

TypeExample
Int, Long42, 42L
Double, Float3.14, 3.14f
Booleantrue
Char'A'
String"Kotlin"
Everything is an object, so 42.toString() and 3.7.toInt() work. There's no automatic conversion: val d: Double = 5 is an error; use 5.0 or 5.toDouble().

String templates

"Hi, $name" and "Total: ${price * qty}", with expressions inside ${ }.

Multi-line strings

kotlin
val text = """
    Line one
    Line two
""".trimIndent()

Useful String functions

length, uppercase(), lowercase(), trim(), split(","), contains("x"), startsWith(), replace(), substring(), toInt(), toIntOrNull().

Constants

const val MAX_LIVES = 5 at the top level or in an object, for compile-time constants.

Example

kotlin
const val MAX_LIVES = 5

fun main() {
    val name = "Asha"
    var score = 10
    score += 5
    val ratio: Double = score / 2.0          // 15 / 2.0 = 7.5
    val big = 3_000_000_000L                 // Long

    println("$name scored $score (ratio $ratio), lives: $MAX_LIVES")
    println("Name length: ${name.length}, upper: ${name.uppercase()}")
    println(3.99.toInt())                  // 3 — truncates
    println("42".toInt() + 1)                // 43
    println("4x2".toIntOrNull() ?: "not a number")
    println(big / 1_000_000_000)             // 3

    val poem = """
        Roses are red,
        Kotlin is neat.
    """.trimIndent()
    println(poem)
    println("a,b,c".split(",").reversed())  // [c, b, a]
}