【问题标题】:How can I create a read-only class member in Scala?如何在 Scala 中创建只读类成员?
【发布时间】:2011-09-05 15:29:15
【问题描述】:

我想创建一个 Scala 类,其中一个 var 在类外部是只读的,但仍然是一个 var。我该怎么做?

如果是 val,则无需执行任何操作。默认情况下,该定义意味着公共访问和只读。

【问题讨论】:

    标签: scala variables member


    【解决方案1】:

    为私有var 定义一个公共“getter”。

    scala> class Foo {
         |   private var _bar = 0
         |
         |   def incBar() { 
         |     _bar += 1 
         |   }
         |
         |   def bar = _bar
         | }
    defined class Foo
    
    scala> val foo = new Foo
    foo: Foo = Foo@1ff83a9
    
    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
               ^
    

    【讨论】:

    • 谢谢。不幸的是,这是唯一的解决方案:(这很糟糕,因为 var 真实姓名正因为如此而变得肮脏。总比暴露我的胆量好。谢谢
    【解决方案2】:

    使用“getter”方法定义特征:

    特质 Foo { 定义栏:T }

    定义一个扩展这个特性的类,并且它有你的变量

    私有类 FooImpl (var bar: T) 扩展 Foo

    适当限制此类的可见性。

    拥有一个专用接口还允许您在运行时使用多个实现类,例如更有效地覆盖特殊情况,延迟加载等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 2013-11-13
      • 2012-08-27
      • 2011-03-13
      • 2021-06-03
      相关资源
      最近更新 更多