Skip to content

Instantly share code, notes, and snippets.

@yenerm
Last active April 15, 2024 18:40
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 yenerm/a7391233236f05fca90eec77ac11dde6 to your computer and use it in GitHub Desktop.
Save yenerm/a7391233236f05fca90eec77ac11dde6 to your computer and use it in GitHub Desktop.
<!-- 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()
}
}
@dturner
Copy link

dturner commented Feb 15, 2022

To update FormatDelegate to accept a default value (see comment) this should be:

class FormatDelegate(defaultValue: String = "") : ReadWriteProperty<Any?, String> {
   private var formattedString: String = defaultValue
   ...
}

@elevenfive
Copy link

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