H. Riantsoa
H. Riantsoa

Reputation: 89

What instructions are executed before main() function in Kotlin?

In Kotlin, it is said that the main function is the entry point (i.e "...where the first instructions of a program are executed...", see here). However, the following code prints 2 before 1 :

fun main(args: Array<String>) {
    println("1")
}

var print_me = println("2")

Why?

Upvotes: 2

Views: 302

Answers (1)

gidds
gidds

Reputation: 18587

First, the JVM loads any required classes.  As part of this, it will run any static initialisers.

Although your code looks like it's not in a class, Kotlin/JVM compiles it to one; that will have a field for print_me.  (How it's done is an implementation detail; it may be a static field on the class, or on an instance referred to through a static field.)  In any case, that field will have an initialiser.

Now, the type of print_me is Unit.  That's because the println() function doesn't return a useful value.  (Its sole reason is its side-effect.)  But the JVM will still run the initialiser, which will happily print "2" before returning Unit which gets assigned to print_me.

Later, once the class has been initialised, the runtime will call your main() function.

Of course, a static initialiser may call anything you like, so it could potentially do all sorts of things before hitting your main() function.  But in practice that doesn't happen too much.

Upvotes: 6

Related Questions