Scala: How to use case keyword without match keyword?
It's just syntactic sugar. In scala, you can use any method that takes a single parameter as a binary operator.
Example:
class Foo(x: String) {
def ^^(pf: PartialFunction[String, Int]): Option[Int] =
if (pf.isDefinedAt(x)) Some(pf(x)) else None
}
val foo = new Foo("bar")
foo ^^ {
case "baz" => 41
case "bar" => 42
}
// result: Some(42)
As you mentioned, you can use a block with the case keyword to create a partial function.
val doubleIntGtThree: PartialFunction[Int, Int] = {
case x: Int if x > 3 => x * 2
}
doubleIntGtThree(4) // return 8
doubleIntGtThree(2) //throws a matchError