【发布时间】:2020-06-13 08:08:19
【问题描述】:
这是我的代码。
class Repository(context: Context) {
// Can access 'context' from here
val mSharedPrefsProperties = context
.getSharedPreferences(context.packageName.plus(".properties"), Context.MODE_PRIVATE)
// Can't access 'context' in this function (unresolved reference: context)
private fun getApiKey(): String {
val apiKeys = context.resources.getStringArray(R.array.api_keys)
val random = Random().nextInt(apiKeys.size)
return apiKeys[random]
}
}
有没有办法从函数内部的构造函数访问属性,还是我需要将它们设为实例/局部变量?
【问题讨论】:
标签: android kotlin constructor scope instance-variables