Home > front end >  Kotlin returning kotlin.Unit in result
Kotlin returning kotlin.Unit in result

Time:01-04

fun main() {
    val greeting = birthdayGreeting()
    println(greeting)
}
fun birthdayGreeting(): String {
        val nameGreeting= println("Happy Birthday, Rover!")
        val ageGreeting=println("You are now 5 years old!")
        return "$nameGreeting\n$ageGreeting"
    }

I am a newbie in kotlin language and recently on kotlin playground when i ran this code i got the output as:

Happy Birthday, Rover!
You are now 5 years old!
kotlin.Unit
kotlin.Unit

I searched the internet where it said it happens when the function is void (Unit) but here the return type of function is string. So why does it shows kotlin.Unit

I was expecting: Happy Birthday, Rover! You are now 5 years old! but i got : Happy Birthday, Rover! You are now 5 years old! kotin.Unit Kotlin.Unit

CodePudding user response:

In birthdayGreeting() function you're using println twice.

println return type is Unit.

CodePudding user response:

When you do this:

val x = println("hello")
println(x)

... then you'll get this as an output:

hello
kotlin.Unit

That's because first you print String "hello" and then you print whatever the statement println returned. And as println doesn't return anything (which in kotlins world is kotlin.Unit) then it prints kotlin.Unit.

In your case maybe what you wanted was something like this:

fun main() {
    val greeting = birthdayGreeting()
    println(greeting)
}
fun birthdayGreeting(): String {
    val nameGreeting = "Happy Birthday, Rover!"
    val ageGreeting = "You are now 5 years old!"
    return "$nameGreeting\n$ageGreeting"
}
  • Related