Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a final field in Kotlin?

Tags:

kotlin

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?

like image 654
Johnny Avatar asked Jun 13 '16 14:06

Johnny


People also ask

Does final variable need to be initialized?

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.

Can final field be initialized in constructor?

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.


1 Answers

You can set val value in init block:

class MyClass {

    val s: String

    init {
        s = "value"
    }

}
like image 58
Cortwave Avatar answered Sep 29 '22 12:09

Cortwave