Just learning Kotlin In the first code down below there is the val
keyword right in the other code there is not,
what is the different here if the val
and var
is omitted?
class Person(val firstName: String, val lastName: String) {
}
class Person(firstName: String, lastName: String) {
}
If you omit
val
orvar
in in a constructor, then the only places that can access these parameters are initialization statements that are evaluated at construction time. See https://kotlinlang.org/docs/reference/classes.htmlThis is useful when you want to do something with a value before storing it. In Java you would put that code a constructor body
But it also works for delegation using
by
Or in property delegation
Note: the closure is captured at initialization time, the values are therefore still available when
lazy
evaluates eventually.