Search code examples
androidkotlinconstructorscopeinstance-variables

How to use a property from a constructor inside an instance method in Kotin?


This is my code.

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]
    }
}

Is there a way to access the properties from the constructor inside functions or do I need to make them a instance/local variable?


Solution

  • Simple constructor parameters don't become properties of your class. That only happens by explitly making them var or val. You can, nevertheless, access those simple params in anything related to initialization, for example:

    class ConstWithArg(param1: String) {
        init {
            println(param1)
        }
    
        val field1 = param1.length
        var field2 = param1.length
    
    }
    

    If you need to access the parameter after construction, it should become a property by making it a val. If you don't want anyone else to access this field outside your class, mark it as private:

    class ConstWithArg(private val param1: String) {
    
        fun useProp(){
            println(param1)
        }
    }