Hi guys, so I have a question regarding lambdas: ...
# getting-started
r
Hi guys, so I have a question regarding lambdas: I have a function like:
Copy code
fun addVisibilityListener(listener: (Int) -> Unit = {})
I want to create a list of listeners, It is possible to have a list of lambdas? or how can I handle that scenario?
a
Copy code
val listeners = mutableListOf<(Int) -> Unit>()

fun addVisibilityListener(listener: (Int) -> Unit = {}) = listeners.add(listener)
Copy code
addVisibilityListener {
    println("First listener got: $it")
}

addVisibilityListener()

addVisibilityListener {
    println("Third listener got: $it")
}

listeners.forEach { listener ->
    listener(0)
}
seems to work just fine
🎉 1
r
Thanks a lot I was not sure on what was the args for the
<>
!
👍 1
m
yes it’s totally possible, I’d recommend to use a typealias for improved readability
Copy code
typealias Listener = (Int) -> Unit

val listeners = mutableListOf<Listener>()
👌 2