Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Kotlin allow write main function with no arguments?

Tags:

kotlin

Recently, I started to learn Kotlin and figured out that the main() function may be written without arguments like this:

fun main() {
    dayOfWeek()
}

How is this possible and what Kotlin is doing under the hood? Java doesn't allow us to do so.

like image 981
Nazarii Moshenskiy Avatar asked Dec 18 '22 17:12

Nazarii Moshenskiy


1 Answers

The signature of main is based on what the Java Virtual Machine expects:

The Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings.

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

public static void main(String[] args) public static void main(String... args)

Ref1, Ref2

So yes, we should define an array string param in the main method. But, as you asked,

How is this possible and what Kotlin does under the hood?

Let's see,

Kotlin Code

// fileName : Main.kt
fun main() {
    println("Hello World!")
}

Compiled Java Code

public final class MainKt {
   public static final void main() {
      String var0 = "Hello World!";
      System.out.println(var0);
   }

   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }
}

As you can see, in the compiled Java code, Kotlin uses method overloading to call main method with String[] argument. From this, we can understand that the Koltin simply helps us to save time and make syntax more readable.

Internally, Kotlin calls the main method with String[] argument.

Tip

If you're using IntelliJ IDEA, you can use the built-in Kotlin tools to see the compiled Java version of the Kotlin code.

  1. Menu > Tools > Kotlin > Show Kotlin Bytecode
  2. Click on the Decompile button

You can find simple guide with screenshots from here

like image 156
theapache64 Avatar answered Jan 07 '23 21:01

theapache64