Skip to content

Instantly share code, notes, and snippets.

@Atternatt
Last active September 21, 2017 04:57
Show Gist options
  • Save Atternatt/1a58135a55d1e28e7fadb8a021dddc7c to your computer and use it in GitHub Desktop.
Save Atternatt/1a58135a55d1e28e7fadb8a021dddc7c to your computer and use it in GitHub Desktop.
Property Deleagtion
class Database(private context: Context) {
val helper: SQLiteOpenHelper by lazy { SQLiteOpenHelper(context,...-) }
val observableProperty: Int by Delegates.observable { thisRef , newValue , oldValue -> doSomething()}
val vetoableProperty: Int by Delegates.vetoable { _ , newValue , oldValue -> return if (oldValue < newValue) true else false }
}
class WeakReferenceProperty<Param>(referencedParam: Param?) : ReadOnlyProperty<Any, Param?> {
val weakReference: WeakReference<Param?> by lazy { WeakReference(referencedParam) }
override fun getValue(thisRef: Any, property: KProperty<*>): Param? {
return weakReference.get()
}
}
class SoftReferenceProperty<Param>(referencedParam: Param?) : ReadOnlyProperty<Any, Param?> {
val softReference: SoftReference<Param?> by lazy { SoftReference(referencedParam) }
override fun getValue(thisRef: Any, property: KProperty<*>): Param? {
return weakReference.get()
}
}
//funciones para obtener las propiedades delegadas
fun <Param> weak(param: Param) = WeakReferenceProperty(param)
fun <Param> soft(param: Param) = SoftReferenceProperty(param)
//uso
class ItemAdapter(private context: Context): RecyclerView.Adapter() {
val weakContext: Context? by weak(context)
val softContext: Context? by soft(context)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment