Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoiding Scala memory leaks - Scala constructors
    text
    copied!<p>I was working through the "Programming in Scala" book, and was struck by a bit of a problem in the implementation of the class <code>Rational</code> in Chapter 6.</p> <p>This is my initial version of the <code>Rational</code> class (based on the book)</p> <pre><code>class Rational(numerator: Int, denominator: Int) { require(denominator != 0) private val g = gcd(numerator.abs, denominator.abs) val numer = numerator / g val denom = denominator / g override def toString = numer + "/" + denom private def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a % b) // other methods go here, neither access g } </code></pre> <p>The problem here is that the field g remains for the lifetime of the class, even if never again accessed. This problem can be seen by running the following mock program:</p> <pre><code>object Test extends Application { val a = new Rational(1, 2) val fields = a.getClass.getDeclaredFields for(field &lt;- fields) { println("Field name: " + field.getName) field.setAccessible(true) println(field.get(a) + "\n") } } </code></pre> <p>Its output is going to be: </p> <pre><code>Field: denom 2 Field: numer 1 Field: g 1 </code></pre> <p>A solution I found at the <a href="http://scala.sygneca.com//code/constructors" rel="noreferrer">Scala Wiki</a> involves the following: </p> <pre><code>class Rational(numerator: Int, denominator: Int) { require(denominator != 0) val (numer, denom) = { val g = gcd(numerator.abs, denominator.abs) (numerator / g, denominator / g) } override def toString = numer + "/" + denom private def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a % b) // other methods go here } </code></pre> <p>Here, the field g is only local to its block, but, running the small test application, I found another field <code>x$1</code> which keeps a copy of the tuple consisting of <code>(numer, denom)</code>!</p> <pre><code>Field: denom 2 Field: numer 1 Field: x$1 (1,2) </code></pre> <p>Is there any way to construct a rational in Scala with the above algorithm, without causing any memory leaks?</p> <p>Thanks,</p> <p>Flaviu Cipcigan</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload