Skip to content

Instantly share code, notes, and snippets.

@basvanmeurs
Created February 11, 2021 09:53
Show Gist options
  • Save basvanmeurs/00461e71cbdcfc1b772a86c3612f49e1 to your computer and use it in GitHub Desktop.
Save basvanmeurs/00461e71cbdcfc1b772a86c3612f49e1 to your computer and use it in GitHub Desktop.
Kotlin Extension function with stateful property
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