0

有没有办法在扩展函数中获取“this”的名称?

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

}
4

2 回答 2

1

我认为你不能那样做。作为解决方法传递名称作为参数:

fun Boolean?.persist(name: String) {
    // ...
     PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(name, this).apply()
}
于 2018-11-23T08:20:57.553 回答
1

你打算做的事情是不可能的。您必须提供nameOfVariable作为参数。扩展函数也可以在不受变量支持的任何值上调用。

委托属性可能是您需要的替代方案。

于 2018-11-23T08:27:42.627 回答