What does Void return type mean in Kotlin

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

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

And I have a mistake

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

After a few changes, I have a working function with zero Void as the return type. But this is not exactly what I need

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

According to the Kotlin Documentation, the Unit Type corresponds to the void type in Java. So the correct function without return value in Kotlin

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

or

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

Question: what does Void mean in Kotlin, how to use it and what is the advantage of such use?

+7
java return-type void kotlin
source share
2 answers

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

Similarly, you can use Integer in Kotlin, which is a Java class (but must use Kotlin Int ). You correctly mentioned both ways of not returning anything. So, in Kotlin Void there is "something"!

The error message you receive tells you exactly that. You specified the class (Java) as the return type, but you did not 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"); } 
+8
source share

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

  • Unit → replace java Void
  • Nothing → 'value that never exists

Now in Kotlin, you can reference Void , just like you can reference any class with Java, but you really shouldn't. Use Unit instead. Also, if you return Unit , you can omit it.

+4
source share

All Articles