4 ms·
I'm not familiar with Scala but I don't understand how it could eliminate the need for Item 14: Use public accessors methods rather than public fields. The poi
by guelo 16y ago
I'm not familiar with Scala but I don't understand how it could eliminate the need for Item 14: Use public accessors methods rather than public fields. The point of using accessor methods is so that you can change the underlying implementation if necessary. If the getters and setters are compiled automatically for you it doesn't seem like you'll be able to change the underlying implementation without also changing the types of the methods.
- unoti 16y agoHere's how it works. When I say: class Kitty { val purrVolume: Int; } What Scala actually produces in Java bytecodes is something like this Java equivalent: public class Kitty { private int purrVolume; public void setPurrVolume(int purrVolume) { this.purrVolume = purrVolume; } public int getPurrVolume() { return purrVolume; } } Later, if you decide that you need to change it to do some special calculations in the getters and setters, you can add that to the Scala code. External users of the class will not need to be recompiled, because under the covers Scala was never actually exposing the public member variable.
- pretzel 16y agoI think you mean var, not val. If you were using val you would do: class Kitty(val purrVolue: Int) which would turn out to be in Java: public class Kitty { private final int purrVolume; public Kitty(final int purrVolume) { this.purrVolume = purrVolume; } public int getPurrVolume() { return purrVolume; } }
- narrator 16y agoOn the Java version you forgot equals() and hashcode(). Scala's case classes give you that for free.
- masklinn 16y ago> If the getters and setters are compiled automatically for you it doesn't seem like you'll be able to change the underlying implementation without also changing the types of the methods. You can trivially replace the auto-generated methods by manually crafted ones, keeping the same types (since they're a direct consequence of the original object's type: a String member will have an accessor of type `() => String` and one of type `String => ()`). If the compiler sees the "public" member already has accessors defined, it doesn't generate them. Could hardly be simpler.