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

  • main()有什么特别之处?还有其他特殊功能吗?
  • 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>) {
}

测试2.kt:

package start
// OK!
fun main(args: Array<String>) {
}
// Error! Conflicting overloads
fun myfun(args: Array<String>) {
}

推荐答案

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.

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

Kotlin相关问答推荐

如何在 Big Data 中使用Inc过滤器?

Jetpack Compose Material3和Material2 Slider onValueChangeFinded()的行为不同

如何定义一个函数来接受任何具有特定字段的数据类

CompositionLocal 究竟如何以及何时隐式设置值?

kotlin 模式匹配如何像 scala 一样工作

使用 Kotlin 的 Springboot 中缺少 ResponseEntity 正文属性

为什么Kotlin不用static inner class来实现带有object关键字的单例呢?

Kotlin中用于调用常量名称的枚举类方法之间的区别

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

如何在 Spring Boot 3 中为内部类提供运行时提示

Saripaar formvalidation 在 kotlin 中第二次不起作用

在 SplashActivity 中显示的 Firebase 应用内消息.如何在 MainActivity 中显示它?

Kotlin:泛型、反射以及类型 T 和 T:Any 之间的区别

如何在 Kotlin 中使用 volatile

变量后的Android问号

片段内的 Kotlin 按钮 onClickListener 事件

TornadoFX 中设置 PrimaryStage 或 Scene 属性的方法

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

导航架构组件 - 未生成 DestinationFragmentArgs

如何在 firebase 数据库中使用 kotlin 协程