Home > Software design >  Why not cast to MutableList since I set .toMutableList()
Why not cast to MutableList since I set .toMutableList()

Time:09-16

I have cast this code to mutable list. But for some reason it still indicate it as a list. This is my code

        return (stringToArray(userSharedPrefs.getString(MY_KEY, null))?.toMutableList()?.distinct()?.reversed() ?: mutableListOf<String>())

But got this error

Type mismatch.
Required:
MutableList<String>
Found:
List<String>

Why it says Found: List<String>

CodePudding user response:

distinct() and reversed() return new Lists, not MutableLists. You need to put toMutableList() after those calls.

return (stringToArray(userSharedPrefs.getString(MY_KEY, null))?.distinct()?.reversed()?.toMutableList() ?: mutableListOf<String>())

However, it would be more robust to follow the idiomatic pattern of returning a read-only List from your function anyway, if you are able to change the return type to List. This function does not need the list to be mutable after it's done with it. The consumer can decide whether it needs a MutableList and use toMutableList() if it needs to.

Also, to clarify terminology. toMutableList() does not cast to a MutableList. It copies the contents into a new MutableList. Casting has a very specific meaning. It means getting the compiler to treat an object instance as a different type without changing the instance that's being referenced. Copying to a MutableList is safe, but casting (using as MutableList) is unsafe and can crash at runtime. Even safe-casting to MutableList with as? MutableList is actually unsafe because some of the MutableLists used under the hood in the Kotlin standard library throw runtime exceptions when you try to mutate them.

  • Related