The following code is taken from Programming in Scala book by Martin Odersky et al. which defines a rational type:
class Rational(n: Int, d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d / g
...
private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
}
Here the value g is only used when the implicit constructor initializes fields numer and denom. Suppose programmer knows that it wont be used anywhere else. In the above case it is still accessible after construction of the Rational object. Which means it will also occupy space since is a private field rather than being a local variable to the constructor.
My question is how do I change this code so that g
is only used while construction and then thrown away?