Similar to using an Object Declaration, you can define the main
function of a Kotlin program using a Companion Object of a class.
package my.program
class App {
companion object {
@JvmStatic fun main(args: Array<String>) {
println("Hello World")
}
}
}
The class name that you will run is the name of your class, in this case is my.program.App
.
The advantage to this method over a top-level function is that the class name to run is more self-evident, and any other functions you add are scoped into the class App
. This is similar to the Object Declaration
example, other than you are in control of instantiating any classes to do further work.
A slight variation that instantiates the class to do the actual "hello":
class App {
companion object {
@JvmStatic fun main(args: Array<String>) {
App().run()
}
}
fun run() {
println("Hello World")
}
}
See also: