The result keeps saying: "Type mismatch: inferred type is Unit but String was expected"

Viewed 2274

I have ran the following code on play.kotlinlang.org but the result keeps saying: Type mismatch: inferred type is Unit but String is expected (I made some changes from the original example code)

I have no idea why its inferring type is Unit. I thought I announced the returning type as String. Is the type of println() Unit or have I just wrote the whole ring function wrong?

fun main(){
    val squid:(String)->String={str->println("I'm $str")}
    //ring(::rabbit)
    ring(squid)
}

fun rabbit(str:String):String{
    println("I'm $str")
    return str
}

fun ring(carrot:(String)->String){
    carrot("a appetiting squid")
}
2 Answers

As Animesh pointed out you aren't returning a String n squid

val squid:(String)->String defines a lambda that takes in a String and returns a String

{str->println("I'm $str")}

A lambda will return the value on the last line of the lambda, but in this case that last value is println("I'm a $str")

println return Unit, or rather, it doesn't return anything (which is what Unit represents). So if you still want to print the String AND return it, rewrite it like so:

{ str -> 
   println("I'm $str")
   str // This string is the value that will now be returned.
}

The lambda returns Unit because println returns Unit.

You can write that line as follows:

 val squid:(String)->String={str-> str.also { println("I'm $it") }}

The standard also extension function lets you use the value in an expression (because it returns the value itself) but "also" do something with it first.

Related