Created
February 11, 2021 09:53
-
-
Save basvanmeurs/00461e71cbdcfc1b772a86c3612f49e1 to your computer and use it in GitHub Desktop.
Kotlin Extension function with stateful property
This file contains 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 TargetClass {} // External class to be extended | |
class Extra(var name: String = "") | |
val state = mutableMapOf<TargetClass, Extra>() | |
fun TargetClass.getState(): Extra { | |
return state.getOrPut(this) { Extra() } | |
} | |
fun TargetClass.setName(v: String) { | |
getState().name = v; | |
} | |
fun A.hello(v: String): String { | |
return "hello ${getState().name}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment