【问题标题】:Public variables in Scala?Scala中的公共变量?
【发布时间】:2012-01-09 00:59:15
【问题描述】:

Scala 中是否还有公共实例变量?我正在阅读涵盖 Scala 2.8 的 Scala 编程。如果我理解正确的话,它声称 2.8 中的 vars 默认是公共的。

我现在正在尝试为 2.9.1.final 编写代码,而实例变量现在默认是私有的?但是我知道没有 public 关键字。 (有趣的是,它似乎曾经在 2.x 系列中的某个时候存在,但它在沿线的某个地方神秘地消失了。)

我是否遗漏了一些明显的东西?

此外,通过扩展,是否有一种简单的方法可以将传递给类构造函数的变量声明为公共的(因为现在这些变量似乎也具有默认的私有可见性)?

示例:

class Instance(label: String, attributes: Array[Int]){
  val f = 0
}

Eclipse 声称labelattributesf 都是私有的。 Scala 2.9.1.final 被用作库。

【问题讨论】:

  • 变量默认是公开的。请发布说明问题的示例代码。

标签: eclipse scala variables public scala-ide


【解决方案1】:

在 scala 中,如果省略修饰符,则实例字段默认为公共:

scala> class Foo { var foo = 1 }
defined class Foo

scala> class Bar { def bar() = { val f = new Foo; f.foo = 5; }}
defined class Bar

不用担心。但是,当你在构造函数中使用变量时,变量不一定会变成字段:

scala> class Foo(foo: Int)
defined class Foo

scala> class Bar { def bar() = { val f = new Foo(5); println(f.foo) }}
<console>:8: error: value foo is not a member of Foo
       class Bar { def bar() = { val f = new Foo(5); println(f.foo) }}
                                                               ^

因此您可以将其声明为 val 或 var 以使其可用:

scala> class Foo(val foo: Int)
defined class Foo

scala> class Bar { def bar() = { val f = new Foo(5); println(f.foo) }}
defined class Bar

请注意,所有字段实际上都是私有的,但是 scala 公开了访问器方法(foo() 和 foo_=(t: Int)) 以使您能够访问这些字段),这就是为什么 scala-ide 说这些字段是私有的(假设您的意思是当您将鼠标悬停在变量上时)。

【讨论】:

  • 啊,好的。这消除了一些混乱。奇怪的是,Eclipse 指出这些变量是私有的,但我仍然可以从另一个类访问它们。这只是 Scala IDE 中的一个错误吗?
  • 添加了 scala-ide 认为它是私有的原因的解释。
猜你喜欢
  • 2022-09-24
  • 2012-10-10
  • 2014-02-17
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 2013-05-10
  • 2013-05-06
  • 2011-05-25
相关资源
最近更新 更多