2011-05-31 70 views

回答

33

定義一個公共的「吸氣」到私人的var

scala> class Foo { 
    | private var _bar = 0 
    | 
    | def incBar() { 
    |  _bar += 1 
    | } 
    | 
    | def bar = _bar 
    | } 
defined class Foo 

scala> val foo = new Foo 
foo: Foo = [email protected] 

scala> foo.bar 
res0: Int = 0 

scala> foo.incBar() 

scala> foo.bar 
res2: Int = 1 

scala> foo.bar = 4 
<console>:7: error: value bar_= is not a member of Foo 
     foo.bar = 4 
     ^
+1

謝謝。不幸的是,這是唯一的解決方案:(它很糟糕,因爲var真正的名字因爲這個而變得很髒,比暴露我的膽量更好。 – 2011-06-02 14:46:37

1

定義的性狀與 「吸氣劑」 的方法:

性狀的Foo { DEF欄:T }

定義延伸此性狀的類,並且其具有您的變量

私人類FooImpl(var bar:T)extends Foo

適當限制此類的可見性。

擁有一個專用接口,您還可以在運行時使用多個實現類,以更有效地覆蓋特殊情況,延遲加載等。