在Scala中,使用private关键字修饰的成员变量只可以被这个类的实例访问。也就是说,这个类的任意一个实例都可以访问这个类在任意实例中定义的私有成员变量。
下面这个例子中,isHigher方法就引用了此类的其他实例中的price变量。
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Stock {
private var price: Double = _
def setPrice(p: Double) {price =p}
def isHigher(that: Stock): Boolean = {this.price > that.price}
}
// Exiting paste mode, now interpreting.
defined class Stock
scala> val s1 = new Stock()
s1: Stock = Stock@72f46e16
scala> val s2 = new Stock()
s2: Stock = Stock@791cbf87
scala> s1.setPrice(10)
scala> s2.setPrice(50)
scala> s1.isHigher(s2)
res2: Boolean = false
那么我们如何定义对象私有的成员变量呢,那就是使用private[this]关键字。这时候,成员变量就只能在对象的实例内部来访问。在同类的其他实例中就不能再引用这个成员变量了。
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Stock {
private[this] var price: Double = _
def setPrice(p: Double) {price =p}
def isHigher(that: Stock): Boolean = {this.price > that.price}
}
// Exiting paste mode, now interpreting.
<console>:15: error: value price is not a member of Stock
def isHigher(that: Stock): Boolean = {this.price > that.price}