https://kotlinlang.org logo
#announcements
Title
# announcements
k

kirillrakhman

02/20/2017, 4:09 PM
A property containing it's own name:
Copy code
object Name {
    operator fun provideDelegate(thisRef: Any?, property: KProperty<*>) = property.name
}

operator fun String.getValue(thisRef: Any?, property: KProperty<*>) = this

val foo by Name

fun main(args: Array<String>) {
    println(foo) //prints "foo"
}
g

Guedes

02/20/2017, 4:18 PM
kirillrakhman: It's really useful when developing for Android and creating a wrapper for, for example, a SharedPreferences where I could do
foo = "My data"
and the
setValue
would do something like:
Copy code
sharedPreferences.edit()
  .putString(property.name, value)
  .apply()
And a similar thing for the `getValue`:
Copy code
sharedPreferences.getString(property.name, null)
k

kirillrakhman

02/20/2017, 4:20 PM
I agree
property.name
is very useful
But my snippet is about a property that contains just its name, nothing else