【发布时间】:2017-12-03 17:38:49
【问题描述】:
我试图在 Kotlin 中创建函数而不返回值。我写了一个类似 Java 的函数,但使用 Kotlin 语法
fun hello(name: String): Void {
println("Hello $name");
}
我有一个错误
错误:函数中需要一个“返回”表达式 块体('{...}')
经过几次更改后,我得到了可以为空的 Void 作为返回类型的工作函数。但这并不是我所需要的
fun hello(name: String): Void? {
println("Hello $name");
return null
}
根据Kotlin documentationUnit类型对应Java中的void类型。所以在 Kotlin 中没有返回值的正确函数是
fun hello(name: String): Unit {
println("Hello $name");
}
或者
fun hello(name: String) {
println("Hello $name");
}
问题是:Void 在 Kotlin 中是什么意思,如何使用,这样使用有什么好处?
【问题讨论】:
标签: java kotlin void return-type