Container Algebraic Data Type in Scala

我的未来我决定 提交于 2019-12-11 07:35:25

问题


Not very familiar with Scala's type system, but here's what I'm trying to do.

I have a function that tries to filter people by first and last name, and if that fails filters by first name only.

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]())
  }

Right now I am returning the filtered Set along with an Algebraic Data Type informing the caller which filter's results were used.

sealed trait MatchResult
case object BothMatch extends MatchResult
case object FirstOnly extends MatchResult
case object NoMatch extends MatchResult

However, returning a tuple of the Set + MatchResult doesn't present a very nice contract for the caller. I'm wondering how I can store my filtered results in my MatchResult.

I thought I could simply change to:

sealed trait MatchResult extends Set[People]
case object BothMatch extends MatchResult
case object FirstOnly extends MatchResult
case object NoMatch extends MatchResult 

But the compiler tells me that I must implement abstract member iterator: Iterator[A]

I'm not sure if I should try to extend Set or somehow make MatchResult a case class that takes a set as a constructor argument.


回答1:


One approach is to use case classes to store any matches as a member.

sealed trait MatchResult
case class BothMatch(results:Set[Person]) extends MatchResult
case class FirstOnly(results:Set[Person]) extends MatchResult
case object NoMatch extends MatchResult 

In Scala, Set is is trait that has abstract members that must be implemented by any implementing class, and that's why you are receiving that error.

In your implementation, you could use these classes by,

(both.nonEmpty, firstOnly.nonEmpty) match {
    case (true, _) => BothMatch(both)
    case (false, true) => FirstOnly(firstOnly)
    case (_, _) => NoMatch
  }


来源:https://stackoverflow.com/questions/47841374/container-algebraic-data-type-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!