Proper way to return exit code from main function


#1

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.


#2

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


#3

Thanks for confirming. I just looked at https://docs.oracle.com/javase/tutorial/getStarted/application/ an indeed void main is used in Java, too. Looks like I had C’s int main in mind.


#4

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.