Skip to content

Instantly share code, notes, and snippets.

@jacobmoncur
Last active January 15, 2016 05:03
Show Gist options
  • Save jacobmoncur/29e5f135d9d6bc1324c9 to your computer and use it in GitHub Desktop.
Save jacobmoncur/29e5f135d9d6bc1324c9 to your computer and use it in GitHub Desktop.

Delegated Properties

class Example {
    var p: String by Delegate()
}


class Delegate {
    operator fun getValue(refr: Any?, prop: KProperty<*>): String {
        return "Thank you for delegating '${property.name}' to me!"
    }

    operator fun setValue(refr: Any?, prop: KProperty<*>, v: String) {
        println("$v assigned to '${property.name}'")
    }
}

val ex = Example()
ex.p = "NEW" // prints "NEW assigned to ‘p’".
val lazyValue: String by lazy {
    "Hello"
}
var counter: Int by Delegates.observable(0) { prop, old, new ->
    println("$old -> $new")
}
var username: String by Delegates.vetoable("None") { prop, old, new ->
    new.isNotEmpty()
}
val frameLayout: FrameLayout by bindView(R.id.frameLayout)
var rememberPin: Boolean by Cacheable("rememberPin", false)
var companyColor: Int by Cacheable("companyColor", Color.BLACK) {
    Bus.post(UpdateColorMessage())
}
class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int     by map
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment