In this post, we will see how to resolve why do I get “Kotlin.Unit” error and how to fix it?
Question:
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 ofvoid
, 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:return
the value you want. This stops the Kotlin compiler from implicitly inserting a return Unit
in there.Alternatively, use an expression-bodied function:
when
expression you used.If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review