Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas

PatilShreyas/1Details.kt.diff Secret

Created Dec 29, 2020
Embed
What would you like to do?
class OrderDetails {
- var fullName: String = ""
- set(value) {
- field = value.split(" ").joinToString(" ") { it.capitalize() }
- }
+ var fullName by CapitalizeDelegate()
- var city: String = ""
- set(value) {
- field = value.split(" ").joinToString(" ") { it.capitalize() }
- }
+ var city by CapitalizeDelegate()
- var coupon: String = "NO COUPON"
- set(value) {
- field = value.toUpperCase()
- }
+ var coupon by UppercaseDelegate()
}
class CapitalizeDelegate : ReadWriteProperty<Any?, String> {
private var formattedString: String = ""
override operator fun getValue(thisRef: Any?, property: KProperty<*>): String = formattedString
override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
formattedString = value.split(" ").joinToString(" ") { it.capitalize() }
}
}
class UppercaseDelegate : ReadWriteProperty<Any?, String> {
private var formattedString: String = ""
override operator fun getValue(thisRef: Any?, property: KProperty<*>): String = formattedString
override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
formattedString = value.toUpperCase()
}
}
fun main() {
val details = OrderDetails()
details.fullName = "john doe"
details.city = "pune"
details.coupon = "abcdef"
println(details.fullName) // prints "John Doe"
println(details.city) // prints "Pune"
println(details.coupon) // prints "ABCDEF"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment