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

s-h*_*ter 1 android parcelable kotlin

这就是我尝试 @Parcelize a HashMap 的方法

@Parcelize
class DataMap : HashMap<String, String>(), Parcelable
Run Code Online (Sandbox Code Playgroud)

但它甚至无法通过以下代码进行编译。

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)
Run Code Online (Sandbox Code Playgroud)

它在这一行抱怨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
Run Code Online (Sandbox Code Playgroud)

Ale*_*nov 5

首先,@Parcelize只关心主构造函数参数,而不关心超类;因为您没有,所以它生成的代码不会从Parcel.

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

@Parcelize
class DataMap(
    val map: HashMap<String, String> = hashMapOf()
) : Parcelable, MutableMap<String, String> by map
Run Code Online (Sandbox Code Playgroud)

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

所有支持类型的集合:List(映射到ArrayList)、Set(映射到LinkedHashSet)、Map(映射到LinkedHashMap);

还有一些具体的实现:ArrayList、LinkedList、SortedSet、NavigableSet、HashSet、LinkedHashSet、TreeSet、SortedMap、NavigableMap、HashMap、LinkedHashMap、TreeMap、ConcurrentHashMap;