Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Void return type mean in Kotlin

Tags:

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?

like image 789
Mara Avatar asked Jun 29 '17 21:06

Mara


People also ask

What does void return type mean?

In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal.

Does void need a return type?

Void functions do not have a return type, but they can do return values.

Is Unit same as void in Kotlin?

Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.

What does return mean Kotlin?

return@ is a statement in Kotlin which helps the developers to return a function to the called function. In simple words, return@ can return any value, anonymous function, simple inline function, or a lambda function.


1 Answers

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") } 
like image 140
Willi Mentzel Avatar answered Oct 06 '22 01:10

Willi Mentzel