Search code examples
scalapattern-matchingscala-option

Scala : Pattern matching with Option[Foo] and parameter of Foo


How can rewrite the following to make it more 'Scala way' or use just one match?

case class Foo(bar: Any)
val fooOpt = Some(Foo("bar as String"))

def isValid(p: Any) = p match {
   case _ @ (_: String | _: Int) => true
   case _ => false
}

//Is it possible to check for the type of bar directly in this if statement?
fooOpt match {
    case Some(f) if isValid(f.bar) => doSomething
    case _ => doSomethingElse
}

One alternative would be using the isInstanceOf.

fooOpt match {
     case Some(f) if f.bar.isInstanceOf[String] => doSomething
     case Some(f) if f.bar.isInstanceOf[Int] => doSomething //could also rewrite to use just one case
     case _ => doSomethingElse
}

Is there other way?


Solution

  • This can all be done in one big pattern match:

    fooOpt match {
       case Some(Foo(_: Int | _: String)) => doSomething
       case _ => doSomethingElse
    }
    

    If you want to get the Int or String out, just split that case:

    fooOpt match {
       case Some(Foo(i: Int)) => doSomething
       case Some(Foo(s: String)) => doSomething
       case _ => doSomethingElse
    }