0

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Yeah cut and paste hell re:return. I altered that before I saw your reply. Thanks. Though I do see there is an explicit way to use return in lambdas eg return @listener s2, though I am yet to try that. I'll mark your lesson as accepted. Thank you.
What sort of situations would we want to name the parameter then (i.e. is there any benefit)?
When I want to use a named parameter: when the lambda takes more than one. Is this something frowned upon? That aside I made my point that this is just experimenting with Kotlin to get a feeling - not specifically to solve an issue.
When a function takes a function as argument for example, or returns a function. Naming the arguments of the argument/returned function makes it easier to understand what the function does. See kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/… for example: naming the Int argument index makes it easier to unerstand what the argument represents.
I'm not questioning you. I am referring to Slaw. But naming parameters is frequently done and my Q was merely on how to do it properly: and you have answered. Thanks,
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.