Pattern matching method calls


Is there a way of using pattern matching to solve this problem?

def myFun(aVar : SomeType) {
   val ans = if (aVar.isX()) "x"
              else if (aVar.isY()) "y"
              else if (aVar.isZ()) "z"
              else ...

The SomeType is an external library class. I wish to find out what sort of thing it is by calling different library isXYZ() methods and then doing certain actions according to the result?


Not sure if using pattern matching is an improvement, but you can (untested):

def myFun(aVar : SomeType) {

** val ans = aVar match {**

** case _ if(aVar.isX()) => “x”**

** case _ if(aVar.isY()) => “y”**

** case _ if(aVar.isZ()) => “z”**

** …**

** }**



If you use this distinction in several places, you can create extractor objects. But I’m also not sure if that is an improvement over if-else, if you do not actually extract a part of the SomeType:

object IsX { def unapply(o: SomeType): Boolean = o.isX }
object IsY { def unapply(o: SomeType): Boolean = o.isY }
object IsZ { def unapply(o: SomeType): Boolean = o.isZ }

val ans = aVar match {
    case IsX() => "x"
    case IsY() => "y"
    case IsZ() => "z"

But if you are extracting some value, you can define unapply to return an Option of your extracted type and match will assign that to a pattern variable, which is a more typical use case for pattern matching:

object IsX { def unapply(o: SomeType): Option[XType] = if(o.isX) Some(o.asXType()) else None }

aVar match {
    case IsX(xTypeVar) => xTypeVar.doSomething()
    // ...

See also