Reflecting the name of 'this' in a Kotlin extension function

618 views Asked by At

Is there a way to get the name of 'this' in an extension function?

fun Boolean?.persist() {

   if (this == null) return   // Do Nothing

   val nameOfVariable:String = //get the name of the variable? 

   // Persist variable
   PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(nameOfVariable, this).apply()

}
2

There are 2 answers

0
tynn On BEST ANSWER

What you intend to do is not possible. You'd have to provide the nameOfVariable as a parameter. The extension function could be called on any value not being backed by a variable as well.

Delegated Properties could be an alternative for your needs.

0
Sergio On

I think you can't do that. As workaround pass name as a parameter:

fun Boolean?.persist(name: String) {
    // ...
     PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(name, this).apply()
}