在Kotlin中,创建main函数的方式与Java略有不同。在Kotlin中,main函数是程序的入口点,通常位于顶层(文件的最外层)或者类的伴生对象中。以下是两种创建main函数的方式:
1. 在文件的顶层创建 main 函数:
在文件的最外层,直接创建 main 函数:
class KotlinDemo {
}
fun filterEndsWith() {
val numbers = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredNumbers = numbers.filter { (key,value) -> key.endsWith("1") && value > 10}
println(filteredNumbers)
}
// 在Kotlin中,main函数是程序的入口点,通常位于顶层(文件的最外层)或者类的伴生对象中
fun main() {
filterEndsWith()
}
2. 在类的伴生对象中创建 main 函数:
在类中,通过伴生对象的方式创建 main 函数,这是在面向对象编程时的一种常见做法:
class KotlinDemo {
companion object {
@JvmStatic
fun main(args: Array<String>) {
filterEndsWith()
}
}
}
fun filterEndsWith() {
val numbers = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredNumbers = numbers.filter { (key,value) -> key.endsWith("1") && value > 10}
println(filteredNumbers)
}
class KotlinDemo { companion object { @JvmStatic fun main(args: Array) { filterEndsWith() } } }
// 可以在文件的最外层定义函数,这些函数类似于Java中的静态方法。它们不属于任何类,可以在文件中的任何位置调用 fun filterEndsWith() { val numbers = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11) val filteredNumbers = numbers.filter { (key,value) -> key.endsWith("1") && value > 10} println(filteredNumbers) }
请注意,为了与Java的主函数签名兼容,main 函数的参数为一个 Array<String> 类型。使用 @JvmStatic 注解可以使得该方法成为类的静态方法,方便 Java 调用。
以上两种方式都是合法的,你可以根据项目的结构和需求选择其中之一。在通常情况下,使用文件的顶层方式更为简洁。