3

I have two variables of unknown type. I want to do a pattern match on the combination of the variable types, and then take action based on that -- specifically, I want to implement Comparator[Any] and compare the two variables based on their type. This code produces the desired result:

class SomethingComparator extends util.Comparator[Any] {
  override def compare(o1: Any, o2: Any) = List(o1, o2).map(_.isInstanceOf[Something]) match {
    case List(true, true) => o1.asInstanceOf[Something].someInt.compareTo(o2.asInstanceOf[Something].someInt)
    case List(true, false) => -1
    case List(false, true) => 1
    case _ => 0
  }
}

Is there a way to avoid the map call and pattern match on the types directly, and therefore avoid the two asInstanceOf calls in the first match?

4

1 回答 1

5

This works:

class SomethingComparator extends util.Comparator[Any] {
  override def compare(o1: Any, o2: Any) = (o1, o2) match {
    case (o1:Something, o2:Something) => o1.someInt.compareTo(o2.someInt)
    case (o1:Something, o2:Any) => -1
    case (o1:Any, o2:Something) => 1
    case _ => 0
  }
}
于 2012-07-10T20:21:43.637 回答