Created
August 4, 2023 09:06
-
-
Save khahani/2e93e0ba95e58ec6aca8ae10f0a67d84 to your computer and use it in GitHub Desktop.
Lambda and method reference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output for both performClick calls is "Second".