不太熟悉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
中。
我以为我可以简单地改为:
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
成为一个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 is is trait that has abstract members,这就是您收到该错误的原因。
在您的实现中,您可以使用这些类,
(both.nonEmpty, firstOnly.nonEmpty) match {
case (true, _) => BothMatch(both)
case (false, true) => FirstOnly(firstOnly)
case (_, _) => NoMatch
}