I am not able to define a member varaibe

I have a class

class PreferenceHandler(context: Context){

private var ctx; // ← Error here but I also tried private var _context : Context & private var _context : Context = null

fun saveUsernameToSharedPreference(uname: String){
val _pref = _context.getSharedPreference() // ← I have to access that preference here.
}

}

Help me how can I achieve this?

Thanks

Im not entirely sure what you want to achieve, but try it like this:

class PreferenceHandler(private val context: Context) {

	fun saveUsernameToSharedPreference(uname: String) {
		val _pref = context.getSharedPreference()
	}
}

Is this what you need:

class PreferenceHandler(context: Context){

    private var _context: Context = context

    fun saveUsernameToSharedPreference(uname: String){
        val _pref = _context.getSharedPreference()
    }

}

or perhaps this:

class PreferenceHandler(private var context: Context){

    fun saveUsernameToSharedPreference(uname: String){
        val _pref = context.getSharedPreference()
    }

}
private var context //missing type and value
private var context: Context //missing value
private var context : Context = null //Context can't be null, Context? can

Do you want the field to be null, use:

private var context : Context? = null

Do you never want the field to be null, but don’t you want to initialize it, use:

private lateinit var context : Context

This will throw an exception of accessed without being initialized.

https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties-and-variables

1 Like

Thanks For your help :slight_smile: