August 2018
Intermediate to advanced
380 pages
10h 2m
English
The preceding pattern matching statements are very close to the notion of partial functions in Scala. The same way pattern matching statements have a certain domain of cases that they can handle and throw an exception in all other cases, partial functions are defined on a part of their input domain. For example, the preceding match statement can be converted into a partial function, as follows:
scala> val findSquare: PartialFunction[Any, Int] = { | case x: Int => x * x | case square(s) => s | }findSquare: PartialFunction[Any,Int] = <function1>scala> findSquare(2)res12: Int = 4scala> findSquare(new Dummy(3))res13: Int = 9scala> findSquare("Stuff")scala.MatchError: Stuff (of class java.lang.String) at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:255) ...