Variables, Types and Functions
Harry
· 14 Sep 2026
· 2 views
Advertisement
Values and variables
val pi = 3.14 // read-only, cannot be reassigned
var count = 0 // mutable
count = count + 1
val name: String = "Ada" // explicit type (usually optional)
Prefer val by default and only reach for var when you truly need to reassign — immutable data is easier to reason about.
String templates
Embed values and expressions directly inside strings with $:
val user = "Ada"
val age = 36
println("$user is $age")
println("Next year: ${age + 1}") // braces for expressions
Functions
Functions are declared with fun. Parameters are name: Type, and the return type follows the parameter list:
fun add(a: Int, b: Int): Int {
return a + b
}
// single-expression form — type inferred
fun square(n: Int) = n * n
// default and named arguments
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name"
greet("Ada") // Hello, Ada
greet("Ada", greeting = "Hi") // Hi, Ada
Default and named arguments remove the need for the many overloaded methods you often write in Java.
Everything is an expression
if, when and even try return values, so you assign their result directly:
val max = if (a > b) a else b
val label = when (grade) {
"A", "B" -> "Pass"
"F" -> "Fail"
else -> "Unknown"
}
Key points
- Use
valfor read-only,varfor mutable; preferval. - String templates (
$var,${expr}) replace clumsy concatenation. - Declare functions with
fun; use default and named arguments. ifandwhenare expressions that return a value.