3 ms·
Which post # in the discussion did you have in mind? There's some misdirections in that thread with ideas that didn't survive the javap test (which I think rath
by sixbrx 10y ago
Which post # in the discussion did you have in mind? There's some misdirections in that thread with ideas that didn't survive the javap test (which I think rather makes my point). I may do Scala again in the future and would like to know how to avoid this (without factory methods as I mentioned).
If you mean Paul P/extempore's self described "if you can handle a little perversion" method then - "no thanks", that's pretty bad, I'd rather just do factories.
- paulddraper 10y agoclass Rational(n: Int, d: Int) { require(d != 0) val (numer, denom) = { val g = gcd(n.abs, d.abs) (n / g, d / g) } // ... private def gcd(a: Int, b: Int) = if (b == 0) a else gcd(b, a % b) } Now `g` is a local variable.
- sixbrx 10y agoAs discussed in the thread, that doesn't work given that we're trying to avoid extra storage, it adds an extra tuple member to the class. It's still true as of the latest compiler just like it was in 2009: $ scalac -version Scala compiler version 2.12.1 -- Copyright 2002-2016, LAMP/EPFL and Lightbend, Inc. $ javap -private Rational Compiled from "Rational.scala" public class Rational { private final scala.Tuple2 x$1; private final int numer; private final int denom; public int numer(); public int denom(); private int gcd(int, int); public Rational(int, int); }
- paulddraper 10y agoSure, okay. But the point remains that "you couldn't have local/temporary variables in your class constructors" isn't quite true. FYI, you could avoid that but not without giving up `final`. This isn't exactly unusual. Lots of source languages (e.g., C) don't expose all the abilities of the target language (ASM). I'm surprised you mention this shortcoming compared to Java. I would have mentioned the lack of a Java enumeration equivalent.
- sixbrx 10y agoIt was short for the explanation in the following paragraphs (OK I should have added "without unwanted storage side effects" which was the whole point though). WHich I still haven't seen resolved in a memorable/non-gross way (I do assume extempore's hack works). Even Martin's private[this] idea from that thread was apparently never implemented, I just tried it also. I'm a Scala fan by the way, and this is a solvable problem (the private[this] solution would be fine I think). But it's currently a landmine IMO and an unfortunate because it's such an unforced error.