Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

init method in kotlin dependent on order of variables and init method declaration

Tags:

android

kotlin

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 enter image description here

like image 532
a_local_nobody Avatar asked Jul 20 '19 20:07

a_local_nobody


People also ask

How does init work in Kotlin?

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.

What is the execution order of init block Kotlin?

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.

Is it mandatory in Kotlin to define init block of primary constructor is created?

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.

Which of the following variable declarations is valid in Kotlin?

Kotlin variable is declared using keyword var and val.


1 Answers

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

like image 90
a_local_nobody Avatar answered Oct 22 '22 18:10

a_local_nobody