Reputation: 62155
I'm just learning about classes and objects and Scala, and yesterday I saw something like this:
class Foo(bar: Int) {
def increaseByOne = bar + 1
}
Why am I able to use bar
in method increaseByOne
? I would expect the the method definition complain about not knowing bar
.
I though the right way to define such a class would be
class Foo(x: Int) {
val bar = x
def increaseByOne = bar + 1
}
Upvotes: 2
Views: 83
Reputation: 340693
That's one of the wonderful features of Scala: if you reference constructor argument from any method that is not a constructor, Scala will automatically assign that constructor variable to a field. So effectively Scala translates your first code snippet into the second one for you (with private[this]
modifier).
Moreover, preceding constructor argument with val
/var
will create getters/setters as well:
class Foo(val bar: Int)
val foo = new Foo(42);
println(foo.bar)
Upvotes: 7
Reputation: 10776
In this case bar
is defined as private[this]
and can be acessed within the class definition. You can check it with -Xprint:typer
option:
class Foo extends java.lang.Object with ScalaObject {
<paramaccessor> private[this] val bar: Int = _;
def this(bar: Int): $line1.$read.$iw.$iw.Foo = {
Foo.super.this();
()
}
}
Upvotes: 2