我尝试在Kotlin中创建函数而不返回值.我编写了一个类似于Java的函数,但使用了Kotlin语法
fun hello(name: String): Void {
println("Hello $name");
}
Run Code Online (Sandbox Code Playgroud)
我有一个错误
错误:带有块体('{...}')的函数中需要'return'表达式
经过几次修改后,我得到了具有可空Void作为返回类型的工作函数.但这并不是我所需要的
fun hello(name: String): Void? {
println("Hello $name");
return null
}
Run Code Online (Sandbox Code Playgroud)
根据Kotlin文档,单元类型对应于Java中的void类型.所以在Kotlin中没有返回值的正确函数是
fun hello(name: String): Unit {
println("Hello $name");
}
Run Code Online (Sandbox Code Playgroud)
要么
fun hello(name: String) {
println("Hello $name");
}
Run Code Online (Sandbox Code Playgroud)
问题是:Void在Kotlin 中意味着什么,如何使用它以及这种用法的优点是什么?