Proper way to return exit code from main function

What’s the proper way to return an exit code from a command line application? It works to use exitProcess like

object Main {
    @JvmStatic
    fun main(args: Array<String>) {
        exitProcess(1)
    }
}

but that seems to be somewhat unclean as main is not being returned from that way. I also tried

object Main {
    @JvmStatic
    fun main(args: Array<String>): Int {
        return 1
    }
}

but then Kotlin does not recognize the signature of main as the entry point.

1 Like

exitProcess() is the proper way. The signature of main with void return type is a JVM requirement.

1 Like

Thanks for confirming. I just looked at Lesson: A Closer Look at the "Hello World!" Application (The Java™ Tutorials > Getting Started) an indeed void main is used in Java, too. Looks like I had C’s int main in mind.

The reason that the JVM does not use a return from main is that Java supported multi-threading in the language and restricting the return of an exit code to just the single thread that started the app is way too cumbersome. C on the other hand actually had zero support for threads (threads are handled in libraries, not the language) so being inherently single threaded it made sense to use a return value from main.

3 Likes