我尝试在Kotlin中创建无返回值的函数。我按照Java的写法用Kotlin语法编写了一个函数。
fun hello(name: String): Void {
println("Hello $name");
}
我遇到了一个错误
错误:在具有块体('{...}')的函数中需要 'return' 表达式
经过几次更改后,我得到了一个带有可空 Void 返回类型的可工作函数。但这并不完全是我所需的。
fun hello(name: String): Void? {
println("Hello $name");
return null
}
根据 Kotlin 文档,Unit 类型对应于 Java 中的 void 类型。因此在 Kotlin 中,正确的不返回值的函数应该是: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.htmlfun hello(name: String): Unit {
println("Hello $name");
}
或者
fun hello(name: String) {
println("Hello $name");
}
问题是:Kotlin中的Void
是什么意思,如何使用它以及使用它的优点是什么?