主函数和常规函数有什么区别? [英] What is the difference between main and regular function?

查看:263
本文介绍了主函数和常规函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin允许我创建两个main()函数.但是不允许两个myfun()函数.

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

  • main()有什么特别之处?还有其他特殊功能吗?
  • 我可以在同一包中创建两个静态myfun()函数吗?我希望他们拥有像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>) {
}

推荐答案

由于实际原因,Kotlin允许在同一个程序包中具有多个顶级main函数-这样,每个文件中都可以有一个入口点而不将这些文件移动到其他软件包中.

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.

可能是因为每个具有顶级成员的.kt文件都被编译为相应的类文件,所以这些main函数不会发生冲突,因为它们位于单独的类文件中.

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.

为什么允许main函数而不允许其他顶级函数使用?在同一包中具有具有相同名称和签名的多个功能将使从Kotlin调用时无法区分它们.这对于main函数来说不是问题,因为当将它用作程序的入口点时,需要指定其所在的类名称.

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.

这篇关于主函数和常规函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆