This post originated from an RSS feed registered with Scala Buzz
by Jeff Heon.
Original Post: Instance read-only access modifier
Feed Title: The Careful Programmer
Feed URL: http://thecarefulprogrammer.blogspot.com/feeds/posts/default
Feed Description: A (starting) collection of my musings about programming. I'll brush more often on Scala related topics since I am currently learning it.
Be it in C++, Java, or Scala, I have always been bothered by the fact that an instance of a class has access to the private members of another instance.
Sure, it's mighty useful for copy constructors and other functionalities like adding, but I always felt there should also be a "private read-only" access modifier.
Of course, there is no problem in the case of immutable objects. Here's a Scala example (using Scala version 2.6.1).
class Domino(p: int) { private val points=p
def add(that: Domino) = new Domino(p + that.points)
But what if, for whatever reason, I am using mutable objects?
In the following code, I have no quarrel with the function addToMe, but I am bothered by the function addToOther. I wish I could specify my special "private read-only" access modifier there, so this function would not compile.
Normal Scala code: class MutableDomino(p: int) { private var points=p
What do you think about an instance read-only access modifier?
Is it useful, or is it over the edge?
Post update!
Thanks to Eric's heads up below, I learned about the access modifier.
I can actually go even further that prevent write-access to a private member of another instance, I can block read and write access to it altogether using the "this" qualifier. E.g. : private[this]
Here is a new version of the MutableDomino class with it that will be, rightly so, rejected by the Scala interpreter:
class MutableDomino(p: int) { private var points=p
error: value points is not a member of MutableDomino def addToMe(that: MutableDomino) = { points = points + that.points } ^ error: value points is not a member of MutableDomino def addToOther(that: MutableDomino) { that.points = that.points + points }