SkillByAIOpen interactive version →

Lesson 3 / 25

Variables, Functions and Strings

val, var, type inference, default and named arguments.

The everyday syntax

val declares a read-only reference (assign once) and var a mutable one; prefer val. Types are usually inferred (val count = 3 is an Int) but can be written explicitly (val name: String = "Ada"). Functions are declared with fun; a single-expression function can use = instead of a block. Parameters can have default values, and callers can use named arguments, which removes the need for many overloads. String templates embed values with $name or expressions with ${expr}. Semicolons are optional.

Functions with defaults and named arguments

Fewer overloads, clearer call sites.

fun greet(name: String, greeting: String = "Hello", punctuation: String = "!"): String =
    "$greeting, $name$punctuation"

fun area(width: Int, height: Int) = width * height   // return type inferred as Int

fun main() {
    val user = "Ada"            // inferred String, read-only
    var visits = 0              // mutable
    visits += 1

    println(greet(user))                                  // uses both defaults
    println(greet(user, punctuation = "?"))               // named argument skips greeting
    println("Area is ${area(width = 3, height = 4)}, visits: $visits")
}

val is read-only, not deeply immutable

A val cannot be reassigned, but the object it points to may still change, for example a val list = mutableListOf(1) can still add. Use read-only collection types like List to signal intent.

Quick check: What is the difference between `val` and `var`?

  • `val` objects are always deeply immutable
  • `val` is only for numbers
  • `var` makes a value nullable
  • `val` cannot be reassigned after initialisation; `var` can
Answer

`val` cannot be reassigned after initialisation; `var` can — Prefer val and use var only when reassignment is needed.