Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
}
like image 298
fredoverflow Avatar asked Aug 16 '12 11:08

fredoverflow


People also ask

What is a common case class in Scala?

Case classes are Scala's way to allow pattern matching on objects without requiring a large amount of boilerplate. In the common case, all you need to do is add a single case keyword to each class that you want to be pattern matchable.

Should I learn pattern matching in Scala?

If you have programmed in a functional language before, then you will probably recognize pattern matching. Case classes will be new to you, though. Case classes are Scala's way to allow pattern matching on objects without requiring a large amount of boilerplate.

How to model immutable data in Scala pattern matching?

As we’ve previously discussed in our article on Case Classes, a case class is good for modeling immutable data. It has all vals; this makes it immutable. Let’s see how it helps with Scala pattern matching. For the case class, the compiler assumes the parameters to be vals. However, we can use the ‘var’ keyword to attain mutable fields.

What is the constructor pattern in Scala?

Technically, the specific type of pattern matching shown in these examples is known as a constructor pattern. The Scala standard is that an unapply method returns the case class constructor fields in a tuple that’s wrapped in an Option. The “tuple” part of the solution was shown in the previous lesson.


2 Answers

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
}
like image 77
Kim Stebel Avatar answered Oct 19 '22 02:10

Kim Stebel


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)
}
like image 36
0__ Avatar answered Oct 19 '22 04:10

0__