小编Mar*_*ara的帖子

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 中意味着什么,如何使用它以及这种用法的优点是什么?

java return-type void kotlin

17
推荐指数
2
解决办法
2万
查看次数

标签 统计

java ×1

kotlin ×1

return-type ×1

void ×1