Question

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))
}
Was it helpful?

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)
}

OTHER TIPS

So you want to pass a pattern matching block to another function? That can be done with PartialFunctions, as the following example shows:

def foo(f:PartialFunction[String, Int]) = {
  f("")
}

foo {
  case "" => 0
  case s => s.toInt
}

Your magic type can be written as a structural type that has an unapply method. Depending on what kind of extractor you need, you will need different kinds of unapply or unapplySeq. Below is a simple example.

def foo(x:Int, Pattern: { def unapply(x:Int):Boolean }) {
  x match {
    case Pattern => println("match")
  }
}

foo(1, new { def unapply(x:Int) = x > 0 })

And this is how it's done for lists:

foo(List(1,2,3), new { def unapplySeq(x:List[Int]):Option[List[Int]] = if (x.size >= 3) Some(x) else None })

def foo(x:List[Int], Pattern: { def unapplySeq(x:List[Int]):Option[List[Int]] }) {
  x match {
    case Pattern(a,b,c) => println("match: " + a + b + c)
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top