Java Kotlin 中的 Void 返回类型是什么意思

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44834965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:44:47  来源:igfitidea点击:

What does Void return type mean in Kotlin

javakotlinvoidreturn-type

提问by Mara

I tried to create function without returning value in Kotlin. And I wrote a function like in Java but with Kotlin syntax

我试图在 Kotlin 中创建不返回值的函数。我写了一个类似 Java 的函数,但使用 Kotlin 语法

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

And I've got an error

我有一个错误

Error:A 'return' expression required in a function with a block body ('{...}')

错误:具有块体 ('{...}') 的函数中需要“return”表达式

After couple of changes I've got working function with nullable Void as return type. But it is not exactly what I need

经过几次更改后,我得到了可空 Void 作为返回类型的工作函数。但这并不完全是我需要的

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

According to Kotlin documentationUnit type corresponds to the void type in Java. So the correct function without returning value in Kotlin is

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

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

Or

或者

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

The question is: What does Voidmean in Kotlin, how to use it and what is the advantage of such usage?

问题是:Void在 Kotlin 中是什么意思,如何使用它以及这样使用的好处是什么?

采纳答案by Willi Mentzel

Voidis a plain Java class and has no special meaning in Kotlin.

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

The same way you can use Integerin Kotlin, which is a Java class (but should use Kotlin's Int). You correctly mentioned both ways to not return anything. So, in Kotlin Voidis "something"!

您可以Integer在 Kotlin 中使用相同的方式,它是一个 Java 类(但应该使用 Kotlin 的Int)。你正确地提到了不返回任何东西的两种方式。所以,在 Kotlin 中Void是“东西”!

The error message you get, tells you exactly that. You specified a (Java) class as return type but you didn't use the return statement in the block.

您收到的错误消息准确地告诉您。您指定了一个 (Java) 类作为返回类型,但您没有在块中使用 return 语句。

Stick to this, if you don't want to return anything:

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

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

回答by nhaarman

Voidis an object in Java, and means as much as 'nothing'.
In Kotlin, there are specialized types for 'nothing':

Void是 Java 中的一个对象,与“无”一样多。
在 Kotlin 中,“无”有专门的类型:

  • Unit-> replaces java's void
  • Nothing-> 'a value that never exists'
  • Unit-> 替换 java 的 void
  • Nothing-> '一个永远不存在的值'

Now in Kotlin you canreference Void, just as you can reference any class from Java, but you really shouldn't. Instead, use Unit. Also, if you return Unit, you can omit it.

现在,在科特林你可以参考Void,就像你可以从Java引用任何类,但你真的不应该。相反,使用Unit. 另外,如果你 return Unit,你可以省略它。