【发布时间】:2020-10-26 10:04:55
【问题描述】:
我对泛型函数很陌生(在 java 和 kotlin 中)。我使用了一个允许我恢复列表的功能(感谢SharedPreferences)。这些列表要么是MutableList<Int>、<String>、<Long>,要么是……这是我当前使用的代码(我使用list.toString()保存了列表,前提是它不为空):
fun <T: Any> restoreList(sharedPrefsKey: String, list: MutableList<T>) {
savedGame.getString(sharedPrefsKey, null)?.removeSurrounding("[", "]")?.split(", ")?.forEach { list.add((it.toIntOrNull() ?: it) as T) }
}//"it" is already a String, no need to cast in the "if null" ( ?: ) branch
//warning "Unchecked cast: {Comparable<*> & java.io.Serializable} to T" on "as T"
所以我的目标是知道如何将Strings 安全地转换为 T(作为参数传递的列表中元素的类型)。现在我收到一个警告,想知道我所做的是否正确。我还应该添加in 修饰符吗?例如:list: MutableList<in T>?
【问题讨论】:
-
这个函数应该如何使用?在调用时是否知道它应该返回什么(
MutableList<Int>或MutableList<String>)? -
我认为泛型在这里不合适。您需要知道类型是 Int 还是 String 才能正确处理。您可以将类型具体化,但由于只有两种可接受的类型,并且它们的处理方式不同,因此您应该只有两个单独的函数,一个用于 Ints,一个用于 Strings。
-
我使用此函数的目标是在 mutableList(
Int或String)中添加先前保存的项目(存储为String),这就是为什么我将项目转换为 T (希望这个分别是Int或String)。最后,也许写2个不同的函数是最好的选择。但是,如果我们假设该函数可以被任何类型的列表调用,我如何将 String(保存的数据)转换为 T(作为参数传递的列表元素的类型)?
标签: kotlin casting generic-list generic-type-argument