如何使用 Kotlin 的 Parcelize 对 HashMap 进行 Parcelize?

How to Parcelize a HashMap using Kotlin's Parcelize?

这就是我尝试@Parcelize 一个 HashMap 的结果

@Parcelize
class DataMap : HashMap<String, String>(), Parcelable

但是用下面的代码连编译都编译不了

val data = DataMap()
data.put("a", "One")
data.put("b", "Two")
data.put("c", "Three")

val intent = Intent(this, DetailActivity::class.java)
intent.putExtra(DATA_MAP, data)
startActivity(intent)

它在这一行 intent.putExtra(DATA_MAP, data) 抱怨错误:

Overload resolution ambiguity. All these functions match.

public open fun putExtra(name: String!, value: Parcelable!): Intent! defined in android.content.Intent

public open fun putExtra(name: String!, value: Serializable!): Intent! defined in android.content.Intent

首先,@Parcelize只关心主构造器参数,不关心超类;因为你有 none,它生成的代码不会从 Parcel.

写入或读取任何内容

因此,与其扩展 HashMap(无论如何这是个坏主意),不如将其设为一个字段:

@Parcelize
class DataMap(
    val map: HashMap<String, String> = hashMapOf()
) : Parcelable, MutableMap<String, String> by map

MutableMap<String, String> by map部分让DataMap通过委托所有调用实现接口,所以data.put("a", "One")data.map.put("a", "One")一样。

它也没有实现 Serializable,因此您不会 运行 陷入同样的​​重载歧义。

您可以在 https://kotlinlang.org/docs/tutorials/android-plugin.html 查看支持的类型列表,其中确实包括 HashMap:

collections of all supported types: List (mapped to ArrayList), Set (mapped to LinkedHashSet), Map (mapped to LinkedHashMap);

Also a number of concrete implementations: ArrayList, LinkedList, SortedSet, NavigableSet, HashSet, LinkedHashSet, TreeSet, SortedMap, NavigableMap, HashMap, LinkedHashMap, TreeMap, ConcurrentHashMap;