Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between main and regular function?

Tags:

kotlin

Kotlin allows me to create two main() functions. But does not allow two myfun() functions.

  • What is special about main()? Are there other special functions?
  • Can I create two static myfun() functions in same package? I want them to have file scope like main.

Test1.kt:

package start

fun main(args: Array<String>) {
}

fun myfun(args: Array<String>) {
}

Test2.kt:

package start
// OK!
fun main(args: Array<String>) {
}
// Error! Conflicting overloads
fun myfun(args: Array<String>) {
}
like image 978
random Avatar asked Jan 14 '18 01:01

random


1 Answers

Kotlin allows to have multiple top-level main functions in the same package due to practical reasons — so that one could have an entry point in an each file without moving these files to different packages.

It is possible because each .kt file with top-level members is compiled to the corresponding class file, so these main functions do not clash, because they are located in separate class files.

Why is it allowed for main functions and not for other top-level functions? Having multiple functions with the same name and signature in the same package would make it impossible to distinguish them when calling from Kotlin. This is not a problem for main function, because when it is used as an entry point for a program, it's required to specify the class name where it is located.

like image 76
Ilya Avatar answered Oct 29 '22 12:10

Ilya