RichieHH
RichieHH

Reputation: 2123

Kotlin: naming parameters in lambda

Please ignore the actual "functionality" and concentrate more on the use of lambda here as I am hacking around with lambdas, let, also, run etc to get a feeling for Kotlin.

val listener : (String?)->String = {
            val s2 = it?.also {
            }
                ?: "Null"
            statusText.text=s2
            s2
        }

So this assignment of a lambda to "listener" is just fine.

Could someone tell me why I am unable to assign a name to the first (and only) parameter eg.

  val listener : (s: String?)->String = {
            val s2 = s?.also {
            }
                ?: "Null"
            statusText.text=s2
            s2
        }

In the line "val s2=s?.also..." the compiler complains that "s" is an unresolved reference. If so why is the naming of the parameter legal eg:

val listener : (s: String?)->String = {

Any explanation would be a great help to my understanding.

Upvotes: 0

Views: 881

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

It should be

val listener : (s: String?) -> String = { s ->
    val s2 = s?.also {
    } ?: "Null"
    statusText.text=s2
    s2
}

or simply

val listener : (String?) -> String = { s ->
    val s2 = s?.also {
    } ?: "Null"
    statusText.text=s2
    s2
}

Note that using return in the mambda is incorrect, too.

Upvotes: 4

Related Questions