Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas
Created December 29, 2020 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatilShreyas/d08470155d44aabd8180d28024128585 to your computer and use it in GitHub Desktop.
Save PatilShreyas/d08470155d44aabd8180d28024128585 to your computer and use it in GitHub Desktop.
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