Zorgan
Zorgan

Reputation: 9173

Kotlin compiler says getString() is nullable even though it has a default value

My code:

var users: MutableList<String> = mutableListOf()
lateinit var players: ArrayList<Player>


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val sharedPrefPlayers = activity?.getPreferences(Context.MODE_PRIVATE)
    sharedPrefPlayers?.all?.keys?.forEach {
        val filename = "player_$it"
        val playerSharedPref = activity?.getSharedPreferences(filename, Context.MODE_PRIVATE)
        players.add(Player(playerSharedPref!!.getString("name", ""), playerSharedPref.getInt("age", 0), playerSharedPref.getString("gender", "male")))
    }
    players = arrayListOf()
}

I'm getting a Type Mismatch - Required: String, Found: String? on my getString() call above. I'm not sure how the String is nullable as there is a default String backdrop of "" if "name" is not found.

Also, the getInt() call doesn't have that error.

Any idea?

Upvotes: 3

Views: 1654

Answers (1)

Lakshan Dissanayake
Lakshan Dissanayake

Reputation: 561

According to Android Documentation, this is because SharedPreferences.getString(key, defValue) is nullable.

in other words, the getString(String, String) of SharedPreferences as follows.

@Nullable
String getString(String key, @Nullable String defValue);

So even you passed a non-null string, Kotlin still consider that playerSharedPref!!.getString("name", "") could be null.

You can overcome this issue by assuring that playerSharedPref!!.getString("name", "") to be non-null.

Solution: put !! at the end of playerSharedPref!!.getString("name", ""), so the result will be playerSharedPref!!.getString("name", "")!!

Hope this helps!

Upvotes: 3

Related Questions