Created
October 2, 2019 10:03
-
-
Save wojciech-zurek/4cf7b60188ee6018f41f801eafbecc29 to your computer and use it in GitHub Desktop.
Delegated Properties Example in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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