如何在 Kotin 的实例方法中使用构造函数中的属性?

Nic*_*ico 0 android constructor scope instance-variables kotlin

这是我的代码。

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]
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法从函数内部的构造函数访问属性,还是需要将它们设为实例/局部变量?

app*_*ano 6

只需将var(或val)放在参数上

class Repository(var 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]
    }
}
Run Code Online (Sandbox Code Playgroud)