scala - Constructor parameter names and class member names -
i understand how scala deals constructor parameters, i.e. generating getter val , getter/setter var. have found quite few discussions name clashes between constructor parameters , class members.
for names w/o val & var, expect if they're prefixed this.
, class members instead should used. that's not case.
class a(val a: int) { def m = println("a.a: " + a) } class b(a: int) extends a(2 * a) { override def m = { super.m println("@a: " + a) println("this.a: " + this.a) // @a, not a.a } } object testapp extends app { val b = new b(10) b.m println(b.a); // a.a }
output:
a.a: 20 @a: 10 this.a: 10 20
i feel it's weird there design reason behind it?
as wrote in question scala generates getter val
, when declare val
parameter in a
class, has method m
, field a
, inherited b
class. have a
parameter in b
class, doubled , passed argument super constructor of a
. understand what's going on, turn on option -xprint:typer
repo , paste code, e.g a
represented this:
class extends scala.anyref { <paramaccessor> private[this] val a: int = _; <stable> <accessor> <paramaccessor> def a: int = a.this.a; def <init>(a: int): = { a.super.<init>(); () }; def m: unit = scala.this.predef.println("a.a: ".+(a.this.a)) }
as can see scala created hidden private[this]
field a
parameter. , here representation b
class:
class b extends { <paramaccessor> private[this] val a: int = _; def <init>(a: int): b = { b.super.<init>(2.*(a)); () }; override def m: unit = { b.super.m; println("@a: ".+(b.this.a)); println("this.a: ".+(this.a)) } }
as can see scala defined private[this]
field a
parameter in b
class. because didn't mark val
value, didn't generate new a
getter, still defined a.this.a
, not b.this.a
, that's why r getting 20
when calling b.a
.
as answer, don't think there complex design behind this, looks logical , quite reasonable. if rename a
param in b
class constructor , pass a
, nothing change.
Comments
Post a Comment