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))
}
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.
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.
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.
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.
So you want to pass a pattern matching block to another function? That can be done with PartialFunction
s, as the following example shows:
def foo(f:PartialFunction[String, Int]) = {
f("")
}
foo {
case "" => 0
case s => s.toInt
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With