0
votes

The problem is when I created the instance of my Model class and pass the non-nullable variable to the constructor, the compiler shows the error Type-mismatch. I have fixed the type-mismatch error by making model class variable as nullable

But I couldn't understand the error shown by the compiler.

Model class

class SharedPreferenceEntry (val name:String, val dateOfBirth:Calendar, val email:String)

Helper class SharedPreferencesHelper, where I created an instance of Model class and return that instance from function

fun getPersonalInfo(): SharedPreferenceEntry { // Get data from the SharedPreferences.
        val name = mSharedPreferences.getString(KEY_NAME, "")
        val dobMillis =
            mSharedPreferences.getLong(KEY_DOB, Calendar.getInstance().getTimeInMillis())
        val dateOfBirth: Calendar = Calendar.getInstance()
        dateOfBirth.setTimeInMillis(dobMillis)
        val email = mSharedPreferences.getString(KEY_EMAIL, "")
        // Create and fill a SharedPreferenceEntry model object.
        return SharedPreferenceEntry(name, dateOfBirth, email)
    }
1
val email is most probably a nullable string because mSharedPreferences.getString(..) returns a nullable. And in the constructor of SharedPreferenceEntry you have declared email to be non-nullable. That's the type mismatchdenvercoder9

1 Answers

1
votes

As @sonnet commented, the use of mSharedPreferences.getString(...) will return null if the key is mapped to null. To ensure, the value of mSharedPreferences.getString(...) is non-null, change it to mSharedPreferences.getString(...) ?: "".