首页 文章

Void返回类型在Kotlin中意味着什么

提问于
浏览
15

我尝试在Kotlin中创建函数而不返回值 . 我编写了一个类似于Java的函数,但使用了Kotlin语法

fun hello(name: String): Void {
    println("Hello $name");
}

我有一个错误

错误:具有块体('')的函数中需要'返回'表达式

经过几次修改后,我得到了具有可空Void作为返回类型的工作函数 . 但这并不是我所需要的

fun hello(name: String): Void? {
    println("Hello $name");
    return null
}

根据Kotlin documentation单元类型对应于Java中的void类型 . 所以在Kotlin中没有返回值的正确函数是

fun hello(name: String): Unit {
    println("Hello $name");
}

要么

fun hello(name: String) {
    println("Hello $name");
}

问题是: Void 在Kotlin中意味着什么,如何使用它以及这种用法的优点是什么?

2 回答

  • 18

    Void 是一个普通的Java类,在Kotlin中没有特殊含义 .

    你可以在Kotlin中使用 Integer ,这是一个Java类(但应该使用Kotlin的 Int ) . 你正确地提到了两种不返回任何东西的方法 . 所以,在Kotlin Void 是"something"!

    您收到的错误消息可以准确地告诉您 . 您将(Java)类指定为返回类型,但未在块中使用return语句 .

    坚持这一点,如果你不想归还任何东西:

    fun hello(name: String) {
        println("Hello $name")
    }
    
  • 15

    Void 是Java中的一个对象,意思是'nothing' .
    在Kotlin中,'nothing'有专门的类型:

    • Unit - >替换java的 void

    • Nothing - > 'a value that never exists'

    现在在Kotlin中你可以引用 Void ,就像你可以引用Java中的任何类一样,但你真的不应该这样 . 而是使用 Unit . 此外,如果您返回 Unit ,则可以省略它 .

相关问题