Rasmus Höglund Rasmus Höglund - 3 months ago 7
Scala Question

Scala: check combination of two variables

I want to check if two variables taken in any order can be paired into a specific pair. Basically the below, only it doesn't work because of type erasure at runtime

def combination[A,B](x: Any, y: Any): Option[(A, B)] =
(x, y) match {
case (a: A, b: B) => Some(a, b)
case (b: B, a: A) => Some(a, b)
case _ => None


Is there another way to do the same which would work...

Answer

Note, since it wasn't clear in your message, if you want to pattern-match against a pair of constants (a, b), you may want to consider back-ticks instead of what you're doing :

case (`a`, `b`) => Some(a, b)

On the other hand if you are trying to retrieve the elements of a pair of any values of type (A, B), in any order, you can do it for non-primitive types (i.e. subtypes of AnyRef) :

import scala.reflect.ClassTag
def combination[A, B](x: AnyRef, y: AnyRef)(implicit tagA: ClassTag[A], tagB: ClassTag[B]): Option[(A, B)] = (x, y) match {
  case (a: A, b: B) => Some(a, b)
  case (b: B, a: A) => Some(b, a)
  case _ => None
}
Comments