In kotlin, for any class which has an init
method (I found this example in a ViewModel) why is the following valid:
val variable1 = "nothing"
fun example1() {
variable1
variable2
}
val variable2 = "nothing"
the order in which I declared the variables and the method did not make a difference, I can still access variable2
inside the method, however,
val variable1 = "nothing"
val variable2 = "nothing"
init {
variable1
variable2
variable3
}
val variable3 = "an issue"
gives an error saying that variable3
must be initialized? See this image, I know that example1() isn't used, but it doesn't make a difference if I use it somewhere
Kotlin initThe code inside the init block is the first to be executed when the class is instantiated. The init block is run every time the class is instantiated, with any kind of constructor as we shall see next. Multiple initializer blocks can be written in a class. They'll be executed sequentially as shown below.
Execution order First, default constructor arguments are evaluated, starting with argument to the constructor you call directly, followed by arguments to any delegated constructors. Next, initializers (property initializers and init blocks) are executed in the order that they are defined in the class, top-to-bottom.
The init block is always called after the primary constructor. A class file can have one or more init blocks executing in series i.e. one after another.
Kotlin variable is declared using keyword var and val.
Thanks to CommonsWare for pointing it out.
initializer blocks are not constructors, they are simply used for initializing values, you can even have multiple init blocks as well. However, an initializer block is not a function and therefore it is dependent on the order of variables being declared and used
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