gpt4 book ai didi

scala - 使用密封特征作为 map 的键

转载 作者:行者123 更新时间:2023-12-04 20:01:44 25 4
gpt4 key购买 nike

我正在尝试从密封特征的实例中定义 map 。在以下代码中,Scala 似乎将 key 类型推断为 Product with Serializable with Day :

object Test extends App {
sealed trait Day
case object Sunday extends Day
case object Monday extends Day
case object Tuesday extends Day

val m: Map[Day, Int] = Map(Sunday -> 17, Monday -> 4).withDefaultValue(0)
}

这不编译:
Test.scala:7: error: type mismatch;
found : scala.collection.immutable.Map[Product with Serializable with Test.Day,Int]
required: Map[Test.Day,Int]
Note: Product with Serializable with Test.Day <: Test.Day, but trait Map is invariant in type A.
You may wish to investigate a wildcard type such as `_ <: Test.Day`. (SLS 3.2.10)
val m: Map[Day, Int] = Map(Sunday -> 17, Monday -> 4).withDefaultValue(0)

我可以在 m 的定义中更改 key 类型,但这意味着重复 Product with Serializable with Day在很多地方。我发现的另一个选择是将特征的定义更改为:
sealed trait Day extends Product with Serializable

由于使用密封特征和案例对象而不是枚举有很多优点,我想知道将它们作为键放在 map 中的好方法是什么。

最佳答案

因为 Map需要键具有在 Product 中定义的属性和 Serializable ,所以 Scala 隐式地创建 anonymous classProduct 扩展你的类和 Serializable它提供了 equals 的默认实现和 hash .

object Test extends App {
trait PS extends Product with Serializable
sealed trait Day extends PS
case object Sunday extends Day
case object Monday extends Day
case object Tuesday extends Day

val m: Map[Day, Int] = Map(Sunday -> 17, Monday -> 4).withDefaultValue(0)
}

关于scala - 使用密封特征作为 map 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28773052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com