如何为 putParcelableArrayList 使用通用列表?
How to use generic list for putParcelableArrayList?
使用kotlin,并且有一个函数接受一个泛型列表,并且在lis里面放入一个Bundle以传递给一个片段。
fun createArgs(filters: List<Filters>?): Bundle {
val args = Bundle()
args.putParcelableArrayList(KEY_FILTERS, filters) //<=== does not compile
必须改为
args.putParcelableArrayList(KEY_FILTERS, ArrayList(filters))
正在制作列表的另一个副本。
如何将通用列表设置为Bundle?
How to set a generic list into Bundle?
你不知道。 Bundle
仅限于某些类型,List
不是其中之一。
在大多数情况下(但不总是)List
个实例实际上是 ArrayList
个。所以你可以避免大多数副本:
fun <T> List<T>.asArrayList(): ArrayList<T> = if (this is ArrayList) this else ArrayList(this)
args.putParcelableArrayList(KEY_FILTERS, filters.asArrayList())
Bundle 不会改变您放入其中的列表,因此假设 您 在将其放入 bundle 后也不会改变它应该足够安全。
使用kotlin,并且有一个函数接受一个泛型列表,并且在lis里面放入一个Bundle以传递给一个片段。
fun createArgs(filters: List<Filters>?): Bundle {
val args = Bundle()
args.putParcelableArrayList(KEY_FILTERS, filters) //<=== does not compile
必须改为
args.putParcelableArrayList(KEY_FILTERS, ArrayList(filters))
正在制作列表的另一个副本。
如何将通用列表设置为Bundle?
How to set a generic list into Bundle?
你不知道。 Bundle
仅限于某些类型,List
不是其中之一。
在大多数情况下(但不总是)List
个实例实际上是 ArrayList
个。所以你可以避免大多数副本:
fun <T> List<T>.asArrayList(): ArrayList<T> = if (this is ArrayList) this else ArrayList(this)
args.putParcelableArrayList(KEY_FILTERS, filters.asArrayList())
Bundle 不会改变您放入其中的列表,因此假设 您 在将其放入 bundle 后也不会改变它应该足够安全。