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?
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: