The main function in kotlin:
fun main(args : Array<String>) {
println("Hello, world!")
}
Why is an Array passed in?
The main function in kotlin:
fun main(args : Array<String>) {
println("Hello, world!")
}
Why is an Array passed in?
The signature of main
is based on what the Java Virtual Machine expects:
The method
main
must be declaredpublic, 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)
This is what the Kotlin compiler compiles your main function to. As of Kotlin 1.3, the explicit Array<String>
can be omitted but will still be available in the byte code.
Collections
were not there in JAVA 1. Hence, Array
was the default choice. Also the arguments provided from Command Line are in string format, hence we use Array<String>
. Kotlin, to maintain interoperability with JAVA, followed the same convention. But, with the update to Kotlin 1.3, that too has been omitted. Now you can use main()
function without passing args:Array<String>
.
The array contains the command line arguments passed to your program.
You can also omit it, if you do not want to use them, i.e. you can also just write:
fun main() {
println("Hello, world!")
}
I am already too late to link to the JLS for Test.main
here (s1m0nw1 already did; I just prepared and went away ;-))
But nonetheless I want to add something regarding the choice for String
(i.e. my opinion why String
was chosen): it's probably the most common denominator for all the possible command line arguments. Any
/Object
is too broad; you can only pass numbers or strings in the command line to a program (pipes are handled differently). But having a number type is too narrow, so the only acceptable type that remains is String
which can represent both. Still you need to parse numbers if you want to use them, but that's better then interpreting a string out of numbers ;-)