2017-12-16 2 views
1

스칼라 유형 시스템에는 익숙하지 않지만 여기에 내가하려고하는 것이있다.컨테이너 대수 데이터 유형 스칼라

나는 사람을 이름으로 필터링하려고하는 함수가 있는데, 이름이 필터 인 경우에만 실패합니다.

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 

그러나 컴파일러는 내가 Set을 확장하거나 어떻게 든 MatchResultcase class를 만들려고하는 경우는 내가 must implement abstract member iterator: Iterator[A]

잘 모르겠어요 것을 알려줍니다 그 집합을 생성자 인수로 취합니다.

답변

3

한 가지 방법은 사례 클래스를 사용하여 일치 항목을 구성원으로 저장하는 것입니다.

sealed trait MatchResult 
case class BothMatch(results:Set[Person]) extends MatchResult 
case class FirstOnly(results:Set[Person]) extends MatchResult 
case object NoMatch extends MatchResult 
스칼라에서

, 어떤 구현 클래스에서 구현해야 Set is is trait that has abstract members, 당신은 그 오류를 받고있는 이유입니다. 구현에

, 당신은

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

이 내가 필요 정확히 무엇이며, 이러한 클래스를 사용할 수 있습니다 - 감사합니다! – diplosaurus