Search code examples
scalapattern-matchingfirst-class

Are scala case patterns first class?


Is it possible to pass case patterns as parameters to other functions? Something like this:

def foo(pattern: someMagicType) {
  x match {
    pattern => println("match")
  }
}

def bar() {
  foo(case List(a, b, c))
}

Solution

  • I think Kim Stebel's first answer is close to what you want. A 'pattern match as such' is no isolated entity in Scala. A match can be defined as a Function1 or PartialFunction.

    def foo[A, B](x: A)(pattern: PartialFunction[A, B]): Unit =
      if(pattern.isDefinedAt(x)) println("match")
    
    def bar(list: List[String]): Unit =
      foo(list){ case List("a", "b", "c") => }
    

    Test:

    bar(Nil)
    bar(List("a", "b", "c"))
    

    Alternatively use composition:

    def foo[A, B](x: A)(pattern: PartialFunction[A, B]): Unit = {
      val y = pattern andThen { _ => println("match")}
      if (y.isDefinedAt(x)) y(x)
    }