Let's say I declared a final field with private final String s
(Java) or val 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?
Declaring final variable without initialization If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.
Note that any final field must be initialized before the constructor completes. For static final fields, this means that we can initialize them: upon declaration as shown in the above example. in the static initializer block.
You can set val
value in init block:
class MyClass {
val s: String
init {
s = "value"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With