5

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.

1
  • 1
    I appreciate the time you spent to learn new things rather than using stackoverflow to fix your bugs :D. Commented Apr 22, 2019 at 11:56

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

Which IDE you're using for Kotlin development ? IntelliJ IDEA ?
Minor nitpick: it's the JVM launcher which calls main(String[]) and of course it doesn't know anything about Kotlin.
4

Other languages like C/C++ allow a main function with empty parameter list. Under the hood they are just usual main methods with the parameters being ignored. This feature is purely syntactic to simplify short programs and demo-ware

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.