Sarah Multitasker
Sarah Multitasker

Reputation: 563

Kotlin type is not inferred into generic function

I have a generic function to fetch/get any list out of the SharedPreferences. However, when I wanted to test, that it does not work, when I saved a list of say, Messages and ask for a list of say, Ints, it still worked. It just ignored the type I precised and returned a List of JsonObjects. When I debugged the whole code, I found, that apparently the function does not care about the inferred class type. I´ll first put here the code, so I can explain the problem:

fun <T> getListFromPreferences(preferences : SharedPreferences, key : String)
        : MutableList<T> {
            val listAsString = preferences.getString(key, "")
            val type: Type = object : TypeToken<List<T>>() {}.type
            val gson = SMSApi.gson
            return gson.fromJson<ArrayList<T>>(listAsString, type)
                    ?: ArrayList()
        }

So, what I would expect, was, that when I call the function like this:

PreferenceHelper.getListFromPreferences<Message>(preferences, TEST_KEY)

the "type" variable in the above code should return List. However the result the debugger shows me is: java.util.List<? extends T> I have absolute no idea, why the inferring does not work, but I´d really like it to work to ensure, what I am requesting is actually what I get, for obvious reasions. Does anybody know a reason and a solution for this weird behaviour?

Upvotes: 1

Views: 955

Answers (1)

Due to type erasure, actual type information about T is lost, so basically this method returns List<Any?> (even if you pass Int as T).

To preserve the actual type, you need to declare this method with reified parameter:

inline fun <reified T>  getListFromPreferences(preferences : SharedPreferences, key : String) 
        : MutableList<T> { 
  //... 
}

Upvotes: 2

Related Questions