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?