1

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()

}
Crocodile
  • 5,724
  • 11
  • 41
  • 67
  • 3
    Your `Boolean` isn't a variable, it's an object. A reference to the object may be stored in zero, one, two, ten, or any other number of variables. – Marko Topolnik Nov 23 '18 at 08:49

2 Answers2

2

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.

tynn
  • 38,113
  • 8
  • 108
  • 143
1

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()
}
Sergio
  • 27,326
  • 8
  • 128
  • 149