Last active
April 15, 2024 18:40
-
-
Save yenerm/a7391233236f05fca90eec77ac11dde6 to your computer and use it in GitHub Desktop.
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
<!-- Copyright 2019 Google LLC. | |
SPDX-License-Identifier: Apache-2.0 --> | |
class FormatDelegate : ReadWriteProperty<Any?, String> { | |
private var formattedString: String = "" | |
override fun getValue( | |
thisRef: Any?, | |
property: KProperty<*> | |
): String { | |
return formattedString | |
} | |
override fun setValue( | |
thisRef: Any?, | |
property: KProperty<*>, | |
value: String | |
) { | |
formattedString = value.toLowerCase().capitalize() | |
} | |
} |
Any thoughts on defining an interface rather than using Any?
class Person: UpdateCountable {
override var updateCount: Int = 0
val firstName: String by CapitalizingUpdateCountableDelegate()
val lastName: String by CapitalizingUpdateCountableDelegate()
}
interface UpdateCountable {
var updateCount: Int
}
class CapitalizingUpdateCountableDelegate : ReadWriteProperty<UpdateCountable, String> {
private var formattedString = ""
override fun getValue(thisRef: UpdateCountable,
property: KProperty<*>): String {
return formattedString
}
override fun setValue(thisRef: UpdateCountable,
property: KProperty<*>,
value: String) {
val newValue = value.lowercase().replaceFirstChar { it.uppercase() }
if (newValue != formattedString) {
formattedString = newValue
thisRef.updateCount ++
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To update FormatDelegate to accept a default value (see comment) this should be: