What does Void return type mean in Kotlin

怎甘沉沦 提交于 2021-01-20 17:44:48

问题


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

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 ('{...}')

After couple of changes I've got working function with nullable Void as return type. 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. So the correct function without returning value in Kotlin is

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?


回答1:


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

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

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.

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

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



回答2:


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

  • Unit -> replaces java's void
  • Nothing -> 'a value that never exists'

Now in Kotlin you can reference 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.



来源:https://stackoverflow.com/questions/44834965/what-does-void-return-type-mean-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!