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:
remove the last println statement in main since you’re already printing in result.
OR
make result return a String (instead of printing it) and then print it from main as you’re doing now.
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 ")
}
}
@ivansavchenkogym555 What do you want your function to do — print the era (to the standard output), or return it (to the caller)? (Or both?) Right now it’s a confused mixture…