I have been trying:
class Foo(bar: Int)
vs:
class Foo(private val bar: Int)
and they seem to behave the same although I couldn’t find anywhere saying that (bar: expands to
Int)(private val bar: Int) so my question is, are these
identical/similar?
On a side note, I have been trying to use -Xprint:typer on these code pieces and they
produce the same code except for an extra line in the second one. How do I
read that extra line?
..
class Foo extends scala.AnyRef {
<paramaccessor> private[this] val bar: Int = _;
def <init>(bar: Int): this.Foo = {
Foo.super.<init>();
()
}
}
..
..
class Foo extends scala.AnyRef {
<paramaccessor> private[this] val bar: Int = _;
<stable> <accessor> <paramaccessor> private def bar: Int = Foo.this.bar;
def <init>(bar: Int): this.Foo = {
Foo.super.<init>();
()
}
}
..
bar: IntThis is barely a constructor parameter. If this variable is not used anywhere except the constructor, it remains there. No field is generated. Otherwise
private val barfield is created and value ofbarparameter is assigned to it. No getter is created.private val bar: IntSuch declaration of parameter will create
private val barfield with private getter. This behavior is the same as above no matter if the parameter was used beside the constructor (e.g. intoString()or not).val bar: IntSame as above but Scala-like getter is public
bar: Intin case classesWhen case classes are involved, by default each parameter has
valmodifier.