Search code examples
androidreflectionkotlinkotlin-extensionkotlin-reflect

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


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

}

Solution

  • 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.