How do I initialize a final field in Kotlin?
10,997
Solution 1
You can set val
value in init block:
class MyClass {
val s: String
init {
s = "value"
}
}
Solution 2
You can also initialize the value with by lazy
the value will be initialized the first time it is referred. An example
val s by lazy { RemoteService.result() }
kotlin will guess the type of s from the return type of the expression.
Related videos on Youtube
Author by
Johnny
Updated on September 14, 2022Comments
-
Johnny over 1 year
Let's say I declared a final field with
private final String s
(Java) orval s
(Kotlin). During initialization I want to initialize the field with the result of a call to a remote service. In Java I would be able to initialize it in the constructor (e.g.s = RemoteService.result()
), but in Kotlin I can't figure out how to do that because as far as I can tell the field has to be initialized in the same line it's declared. What's the solution here?