Public variables in Scala?
Asked Answered
M

1

5

Are there public instance variables anymore in Scala? I'm reading Programming in Scala, which covers Scala 2.8. If I'm understanding it correctly, it claims that vars in 2.8 are by default public.

I'm trying to write code for 2.9.1.final now, and instance variables are now by default private? But there's no public keyword that I'm aware of. (Interestingly enough, it appears it used to exist sometime in the 2.x series, but it mysteriously disappeared somewhere along the line.)

Am I missing something obvious?

Also, by extension, is there an easy way to declare a variable passed to a class constructor to be public (since it appears that those also have default private visibility now too)?

Example:

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

Eclipse claims that label, attributes, and f are all private. Scala 2.9.1.final is being used as the library.

Modish answered 29/11, 2011 at 17:22 Comment(1)
Variables are public by default. Please post example code illustrating the problem.Valorize
A
11

In scala, if you omit the modifer, then instance fields are public by default:

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

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

No worries there. However, when you use a variable in a constructor, the variable is not necessarily turned into a field:

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) }}
                                                               ^

so you can declare it as a val or var to have it available:

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

Note that all fields are actually private, but scala exposes accessor methods (foo() and foo_=(t: Int)) to enable you to access the fields), which is why scala-ide says that the fields are private (assuming you mean when you hover over the variable).

Antonia answered 29/11, 2011 at 17:27 Comment(2)
Ah, ok. That clears up some of the confusion. Oddly enough, Eclipse notes that the variables are private, but I'm still able to access them from another class. Is this just a bug in the Scala IDE?Modish
Added explanation of why scala-ide thinks it's private.Antonia

© 2022 - 2024 — McMap. All rights reserved.