September 2018
Intermediate to advanced
398 pages
9h 43m
English
This might not seem obvious, but when a function throws an exception, it breaks referential transparency. In this section, I am going to show you why. First, create a new Scala worksheet and type the following definitions:
case class Rectangle(width: Double, height: Double)def area(r: Rectangle): Double = if (r.width > 5 || r.height > 5) throw new IllegalArgumentException("too big") else r.width * r.height
Then, we will call area with the following arguments:
val area1 = area(3, 2)val area2 = area(4, 2)val total = try { area1 + area2} catch { case e: IllegalArgumentException => 0}
We get total: Double = 14.0. In the preceding code, the area1 and area2 expressions are referentially transparent. ...
Read now
Unlock full access