Resolved: why do I get “Kotlin.Unit” error and how to fix it?

In this post, we will see how to resolve why do I get “Kotlin.Unit” error and how to fix it?


This code above gives the “Kotlin.Unit” error why and how can I fix it? Thanks.
I tried something and it worked but I didn’t understand it here is the code:

Best Answer:

Kotlin functions have to return a value, unlike say, methods in Java, where they can have a return type of void, which means they have no return value.
So how do you write functions that only has side effects? For example, what does println return? What does a Java void function return, from the Kotlin perspective? The answer us that their return type is Unit, and they return the value Unit. The type Unit only has one valid value – Unit.
By default, if you don’t write a return type in a block-bodied function, like in your first code snippet, the return type is Unit, which is exactly why you see kotlin.Unit being printed.
Note that the when expression in the first code snippets contributes nothing to what the function returns. You are generally allowed to put random expressions as their own “statement” in function bodies. For example, this function compiles, but does nothing useful:
So to fix this, you can specify a return type and return the value you want. This stops the Kotlin compiler from implicitly inserting a return Unit in there.
Alternatively, use an expression-bodied function:
The equal sign at the end of the first line indicates that it is an expression-bodied function, and this causes the compiler to try to infer the return type from the when expression you used.

If you have better answer, please add a comment about this, thank you!