Mar*_*ara 17 java return-type void kotlin
我尝试在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 中意味着什么,如何使用它以及这种用法的优点是什么?
nha*_*man 21
Void是Java中的一个对象,并且意味着"没有".
在Kotlin中,有"专属"的特殊类型:
Unit - >替换java的 voidNothing - >'一个永不存在的值'现在在Kotlin你可以参考Void,就像你可以从Java引用任何类,但你真的不应该.相反,使用Unit.此外,如果您返回Unit,则可以省略它.
Wil*_*zel 21
Void 是一个普通的Java类,在Kotlin中没有特殊含义.
你可以Integer在Kotlin中使用相同的方法,这是一个Java类(但应该使用Kotlin Int).你正确地提到了两种不返回任何东西的方法.所以,在Kotlin Void是"东西"!
您收到的错误消息可以准确地告诉您.您将(Java)类指定为返回类型,但未在块中使用return语句.
坚持这一点,如果你不想归还任何东西:
fun hello(name: String) {
println("Hello $name")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20952 次 |
| 最近记录: |