Can I make "public val" but "private var" in Scala in one line?
I.e. Is it possible to make a var that is not assig开发者_Python百科nable from outside of the class ?
Right now, no, there's no way to do that.
You're limited to the following three-line solution:
class Hider {
private[this] var xHidden: Int = 0
def x = xHidden
private def x_=(x0: Int) { xHidden = x0 }
}
Now the class itself is the only one who can manipulate the underlying field xHidden
, while other instances of the class can use the setter method and everyone can see the getter method.
If you don't mind using different names, you can just make the var private and forget the setter (two lines).
There's no "var to me, val to them" keyword.
You could do something like:
class Test {
private var myprivatevar = ""
def publicvar = myprivatevar
}
From the other classes, you would be able to only use publicvar
and as there is no publicvar_=
method, you can't assign to it from outside.
You certainly make something a var and then make it private to the class defining the field.
scala> class Holder(private var someValue: String) {
| def getValueOfOther(other: Holder) = other.someValue
| def combinedWith(holder: Holder) = new Holder(holder1.someValue + " " + holder2.someValue)
| def value = someValue
| }
defined class Holder
scala> val holder1 = new Holder("foo")
holder1: Holder = Holder@1303368e
scala> val holder2 = new Holder("bar")
holder2: Holder = Holder@1453ecec
scala> holder2.getValueOfOther(holder1)
res5: String = foo
scala> val holder3 = holder1 combinedWith holder2
holder3: Holder = Holder@3e2f1b1a
scala> holder3.value
res6: String = foo bar
精彩评论