简体   繁体   English

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

[英]What does Void return type mean in Kotlin

I tried to create function without returning value in Kotlin. 我尝试在Kotlin中创建函数而不返回值。 And I wrote a function like in Java but with Kotlin syntax 我编写了一个类似于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. 经过几次修改后,我得到了具有可空Void作为返回类型的工作函数。 But it is not exactly what I need 但这并不是我所需要的

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

According to Kotlin documentation Unit type corresponds to the void type in Java. 根据Kotlin文档,单元类型对应于Java中的void类型。 So the correct function without returning value in Kotlin is 所以在Kotlin中没有返回值的正确函数是

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

Or 要么

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

The question is: What does Void mean in Kotlin, how to use it and what is the advantage of such usage? 问题是: Void在Kotlin中意味着什么,如何使用它以及这种用法的优势是什么?

Void is an object in Java, and means as much as 'nothing'. Void是Java中的一个对象,并且意味着“没有”。
In Kotlin, there are specialized types for 'nothing': 在Kotlin中,有“专属”的特殊类型:

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

Now in Kotlin you can reference Void , just as you can reference any class from Java, but you really shouldn't. 现在,在科特林可以参考Void ,就像你可以从Java引用任何类,但你真的不应该。 Instead, use Unit . 相反,使用Unit Also, if you return Unit , you can omit it. 此外,如果您返回Unit ,则可以省略它。

Void is a plain Java class and has no special meaning in Kotlin. Void是一个普通的Java类,在Kotlin中没有特殊含义。

The same way you can use Integer in Kotlin, which is a Java class (but should use Kotlin's Int ). 你可以在Kotlin中使用Integer ,这是一个Java类(但应该使用Kotlin的Int )。 You correctly mentioned both ways to not return anything. 你正确地提到了两种不返回任何东西的方法。 So, in Kotlin Void is "something"! 所以,在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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM