[英]Container Algebraic Data Type in Scala
不太熟悉Scala的类型系统,但这就是我想要做的。
我有一个功能,试图按名字和姓氏过滤人,如果失败只按名字过滤。
case class Person(id: Int, first: String, last:String)
def(people: Set[Person], firstName: String, lastName: String): (MatchResult, Set[Person]) =
val (both, firstOnly) = people.filter(_.first == firstName).partition(_.last == lastName)
(both.nonEmpty, firstOnly.nonEmpty) match {
case (true, _) => (BothMatch, both)
case (false, true) => (FirstOnly, firstOnly)
case (_, _) => (NoMatch, Set[Person]())
}
现在我将返回过滤后的Set
以及代数数据类型,通知调用者使用了哪个过滤器的结果。
sealed trait MatchResult
case object BothMatch extends MatchResult
case object FirstOnly extends MatchResult
case object NoMatch extends MatchResult
但是,返回Set
+ MatchResult
的元组并不MatchResult
调用者提供非常好的合同。 我想知道如何将我的过滤结果存储在我的MatchResult
。
我以为我可以简单地改为:
sealed trait MatchResult extends Set[People]
case object BothMatch extends MatchResult
case object FirstOnly extends MatchResult
case object NoMatch extends MatchResult
但编译器告诉我,我must implement abstract member iterator: Iterator[A]
我不确定我是否应该尝试扩展Set
或以某种方式使MatchResult
成为一个将set作为构造函数参数的case class
。
一种方法是使用案例类将任何匹配存储为成员。
sealed trait MatchResult
case class BothMatch(results:Set[Person]) extends MatchResult
case class FirstOnly(results:Set[Person]) extends MatchResult
case object NoMatch extends MatchResult
在Scala中, Set是具有抽象成员的特征 ,必须由任何实现类实现,这就是您收到该错误的原因。
在您的实现中,您可以使用这些类,
(both.nonEmpty, firstOnly.nonEmpty) match {
case (true, _) => BothMatch(both)
case (false, true) => FirstOnly(firstOnly)
case (_, _) => NoMatch
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.