Search code examples
scalascala-collectionsalgebraic-data-types

Container Algebraic Data Type in Scala


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.


Solution

  • 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
      }