Skip to content

Instantly share code, notes, and snippets.

@wojciech-zurek
Created October 2, 2019 10:03
Show Gist options
  • Save wojciech-zurek/4cf7b60188ee6018f41f801eafbecc29 to your computer and use it in GitHub Desktop.
Save wojciech-zurek/4cf7b60188ee6018f41f801eafbecc29 to your computer and use it in GitHub Desktop.
Delegated Properties Example in Kotlin
import ExampleDelegates.accumulator
import ExampleDelegates.uppercase
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun main() {
val person = Person("ala1222", 12)
println(person.name)//ALA1222
println(person.balance) //12
person.balance = 30
println(person.balance)//42
}
class Person {
var name: String by uppercase()
var balance: Int by accumulator()
constructor(name: String, balance: Int) {
this.name = name
this.balance = balance
}
}
object ExampleDelegates {
public fun uppercase(): ReadWriteProperty<Any?, String> = UpperCase()
public fun accumulator(): ReadWriteProperty<Any?, Int> = Accumulator()
private class UpperCase : ReadWriteProperty<Any?, String> {
private var value: String? = null
public override operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return value ?: throw IllegalStateException(
"Property ${property.name} should be initialized before get."
)
}
public override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
this.value = value.toUpperCase()
}
}
private class Accumulator : ReadWriteProperty<Any?, Int> {
private var value: Int = 0
public override operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return value
}
public override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
this.value = this.value.plus(value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment