Menu
Home
Log in / Register
 
Home arrow Computer Science arrow Building Applications with Scala
Source

Scala PartialFunction without OO using case statements in Scala REPL

Following is a Scala PartialFunction without OO using case statements in 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:PartialFunction[Int, Int] = {

| case n: Int if n != 0 => n / n

I }

positiveNumber: PartialFunction[Int,Int] = scala>

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

scala>println( positiveNumber.isDefinedAt(0) )

false

scala>

scala>println( positiveNumber(6) )

1

scala>println( positiveNumber(0) ) scala.MatchError: 0 (of class java.lang.Integer)

at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:253) at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:251) at $anonfun$1.applyOrElse(:11) at $anonfun$1.applyOrElse(:11)

at scala.runtime.AbstractPartialFunction$mcII$sp.apply$mcII$sp (AbstractPartialFunction.scala:36)

... 32 elided scala>

Scala was a more fluent way to work with PartialFunction using the case statements. When you use the case statements, you don't need to supply the apply and isDefinedAt functions, since the Pattern Matcher takes care of that.

 
Source
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Mathematics
Political science
Philosophy
Psychology
Religion
Sociology
Travel