Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public variables in Scala?

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.

like image 367
Kevin Li Avatar asked Nov 29 '11 17:11

Kevin Li


People also ask

What is a public variable?

Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only to the class to which they belong. Protected variables, are variables that are visible only to the class to which they belong, and any subclasses.

What are the different scopes for variables in Scala?

There are three types of scope for variables in Scala (Source: Scala- Variables): Local variables. Fields. Method Parameters.


1 Answers

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).

like image 66
Matthew Farwell Avatar answered Oct 07 '22 17:10

Matthew Farwell