Kotlin.Unit error

Guys am a beginner and i can’t undertsand why; when i run this code i get “Kotlin.Unit” message under the solution !! i would really appreciate any helpp thankss !!

Code :

fun main() { 
    val coin1 = flippingCoins()
    println ("Side : ${coin1.side} ")
    println (" ${coin1.result()}")}
     // main 
class flippingCoins   { 
    var side = (1..2).random()
    fun result() { 
    if (side==1) println("ur coin landed tail ")
    else println ("ur coin landed head ")
                 } 

result doesn’t return anything: there’s no return statement in it.

When that happens kotlin makes the function “magically” return Unit, think of that as a placeholder for “not returning anything”.
In main you’re printing coin1.result(), which is Unit.

To fix that you can:

  1. remove the last println statement in main since you’re already printing in result.
    OR
  2. make result return a String (instead of printing it) and then print it from main as you’re doing now.
2 Likes

Thanks for the quick Reply !!
i went with your second suggestion and it worked fine!!

Here is the code if anyone ever runs to the same problems

fun main() { 
    val coin1 = flippingCoins()
    println ("Side : ${coin1.side} ")
    println ("${coin1.result()}")}
     // main 
class flippingCoins   { 
    var side = (1..2).random()
    fun result() : String { 
    if (side==1) return ("Your coin landed tail ")
    else return ("Your coin landed head ") 
    } 
}

Note that you don’t have to duplicate the return into both branches, this is equivalent:

fun result(): String { 
    return if (side == 1) "Your coin landed tail "
    else "Your coin landed head "
} 

Or even shorter with an expression body, where you don’t need the return at all`:

fun result() = 
    if (side == 1) "Your coin landed tail "
    else "Your coin landed head "
1 Like