Skip to content

Instantly share code, notes, and snippets.

@igorwojda
Created January 17, 2020 09:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorwojda/c9db756ef861b430d21a74903b597e32 to your computer and use it in GitHub Desktop.
Save igorwojda/c9db756ef861b430d21a74903b597e32 to your computer and use it in GitHub Desktop.
Evolution of the class property
// EVOLUTION OF CLASS PROPERTY
// The presented code is in Kotlin, but the problem itself is not language-specific
// Client usage
fun main() {
Evolution1().setName("Igor")
Evolution2().name = "Igor"
Evolution3().name = "Igor"
Evolution4().name = "Igor"
}
// Internal implementations of "name" property
// Before setters
class Evolution1 {
private var name: String = ""
fun setName(name: String) {
val changed = this.name != name
this.name = name
if(changed) {
notifyValueChanged()
}
}
private fun notifyValueChanged() {
Timber.d("value changed $name")
}
}
// Utilising setters
class Evolution2 {
var name: String = ""
set(value) {
field = value
Timber.d("value changed $value")
}
}
// Utilizing Kotlin builtin observable delegate
class Evolution3 {
var name by Delegates.observable("") { _, _, new ->
Timber.d("value changed $new")
}
}
// Utilizing custom observe delegate
class Evolution4 {
var name by observer("") {
Timber.d("value changed $it")
}
}
// Generic helper delegate
private inline fun <T> observer(
initialValue: T,
crossinline onChange: (newValue: T) -> Unit
):
ReadWriteProperty<Any?, T> =
object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) =
onChange(newValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment