Partial functions

Partial functions are great for function composition. They can operate with case statements as we just learned from Pattern Matcher. Partial functions are great in the sense of function composition. They allow us to define a function in steps. Scala frameworks and libraries use this feature a lot to create abstractions and callback mechanisms. It's also possible to check if a partial function is being supplied or not.

Partial functions are predictable, because the caller can check beforehand if the value will be applied to the partial function or not. Partial function can be coded with or without caselike statements.

Simple Partial function in Scala REPL

Following is a simple Partial function using Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>val positiveNumber = new PartialFunction[Int, Int] {

| def apply(n:Int) = n / n | def isDefinedAt(n:Int) = n != 0 | }

positiveNumber: PartialFunction[Int,Int] = scala>

scala>println( positiveNumber.isDefinedAt(6) ) true

scala>println( positiveNumber.isDefinedAt(0) )



scala>println( positiveNumber(6) )


scala>println( positiveNumber(0) )

java.lang.ArithmeticException: / by zero at $anon$1.apply$mcII$sp(:12)

... 32 elided scala>

Partial functions are Scala classes. They have some methods you need to provide, for instance, apply and isDefinedAt. The function isDefinedAt is used by the caller to check if the PartialFunction will accept and operate with the value supplied. The apply function will do the work when the PartialFunction is executed by Scala.

< Prev   CONTENTS   Source   Next >