Joshua Hansen
09/12/2025, 4:45 PMval at all somewhere other that its declaration site.
class Test {
private val test: String
init {
test = "Hello"
}
}Chrimaeon
09/12/2025, 4:58 PMThe primary constructor initializes a class instance and its properties in the class header. The class header can’t contain any runnable code. If you want to run some code during object creation, use initializer blocks inside the class body. Initializer blocks are declared with thehttps://kotlinlang.org/docs/classes.html#constructorskeyword followed by curly braces. Write any code that you want to run within the curly braces.init
Jonathan
09/12/2025, 4:59 PMtest again in the initializer block.Jonathan
09/12/2025, 5:00 PMclass Test {
private val test: String
init {
test = "Hello"
test = "Hello, again"
}
}
This is a compiler errorloke
09/12/2025, 6:33 PMNorbert Kiesel
09/12/2025, 6:37 PMval variables can also be be initialized subsequently. Example:
fun sample(cond: Boolean) {
val f: Int
if (cond) {
f = 3
} else {
f = 6
}
println(f / 2)
}
The compiler also here enforces that f is always initialized before used. This sometimes is helpful if the code to initialize a val variable is complicated or if you want to set multiple val based on the same condition.