Skip to content

Instantly share code, notes, and snippets.

@khahani
Created August 4, 2023 09:06
Show Gist options
  • Select an option

  • Save khahani/2e93e0ba95e58ec6aca8ae10f0a67d84 to your computer and use it in GitHub Desktop.

Select an option

Save khahani/2e93e0ba95e58ec6aca8ae10f0a67d84 to your computer and use it in GitHub Desktop.
Lambda and method reference
class Button(
private val onClick: () -> Unit
) {
fun performClick() {
onClick()
}
}
class ButtonClickListener(
var name: String
) {
fun onClick() {
println(name)
}
}
class ScreenView {
var listener: ButtonClickListener = ButtonClickListener("First")
val buttonLambda = Button { listener.onClick() }
val buttonReference = Button(listener::onClick)
}
fun main() {
val screenView = ScreenView()
screenView.listener.name = "Second"
screenView.buttonLambda.performClick()
screenView.buttonReference.performClick()
}
@khahani
Copy link
Author

khahani commented Aug 4, 2023

Output for both performClick calls is "Second".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment