Issue
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
Solution
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"
Answered By - Rafa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.