Reputation: 902
Why kotlin does not allow main() function within class just like Java? Why this is allowed outside of the class? Is not it violating OOP principle? I am puzzled!
class Person ( var name : String, var age : Int) {
// putting main here
fun main(args : Array<String>) {
val person = Person("Neek", 34)
println("my name is ${person.name}")
println("my name is ${person.age}")
}
}
Tried to include main() within in a class, I get following error.
warning: parameter 'args' is never used
fun main(args : Array<String>) {
no main manifest attribute
Upvotes: 2
Views: 7108
Reputation: 71
main method and the other methods need to inside the companion object block
class TestMainMethod {
companion object {
@JvmStatic
fun main(args: Array<String>) {
testFunc()
}
fun testFunc() {
}
}
}
Upvotes: 1
Reputation: 10517
You can write the main
method on a Kotlin class, it has to be inside the companion object
class SuperCoolProgram {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println("Hello Super Cool Program")
}
}
}
Static methods can only be written inside the companion object
because it is the only static
Upvotes: 13
Reputation: 3349
Kotlin as a language doesn't enforce that you go OOP. Java is one of the only ones that actually makes you wrap everything you do inside of a class.
You can actually write all of your code at the file level in Kotlin across multiple different files. No classes needed.
If you decompile the code and look at it, what's happening in the file where you've declared
fun main(args: Array<String>) {..}
is that it's being wrapped in a class that has the same name as the file that it's in.
If you have the above code in a file called Foo.kt, this is what's actually being generated
class FooKt {
public static void main(String[] args) { }
}
Where the name of the class is the name of the file + "Kt"
Upvotes: 6