Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is interesting! If you put the class definitions into a file and compile it using <code>scalac -print test.scala</code> you will see something like this,</p> <pre><code>[[syntax trees at end of cleanup]] // scala package &lt;empty&gt; { class A extends Object { def g(): String = A.f(); def &lt;init&gt;(): A = { A.super.&lt;init&gt;(); () } }; object A extends Object { private[this] val f: String = _; &lt;stable&gt; &lt;accessor&gt; def f(): String = A.this.f; def &lt;init&gt;(): A.type = { A.super.&lt;init&gt;(); A.this.f = "Object A"; () } }; class B extends A { &lt;synthetic&gt; private[this] val x$1: runtime.BoxedUnit = _; def &lt;init&gt;(): B = { B.super.&lt;init&gt;(); B.this.x$1 = { case &lt;synthetic&gt; val x1: String = ("Object B": String("Object B")); case5(){ if (A.f().==(x1)) { val x2: String = x1; matchEnd4(scala.runtime.BoxedUnit.UNIT) } else case6() }; case6(){ matchEnd4(throw new MatchError(x1)) }; matchEnd4(x: runtime.BoxedUnit){ scala.runtime.BoxedUnit.UNIT } }; () } } } </code></pre> <p>This shows that the compiler creates a class <code>B</code> with an initialization that performs a match checking to see that the value you used in override the <code>val A.f</code> is equal to the original value <code>if (A.f().==(x1))</code>. Doesn't seem to be too useful right? If they're not equal it throws the match error by calling <code>case6()</code>. We can confirm this by changing the definition of the <code>class B</code> to <code>override val A.f = "Object A"</code>.</p> <pre><code>class B extends A { override val A.f = "Object A" } scala&gt; val b = new B b: B = B@1fc6dc6 </code></pre> <p>So how to fix it? You can just do this,</p> <pre><code>class B extends A { override def g = "Object B" } scala&gt; val b = new B b: B = B@19bdb65 scala&gt; b.g res1: String = Object B </code></pre> <p>or</p> <pre><code>class B extends A { val f = "Object B" } scala&gt; val b = new B b: B = B@1e5ed7b scala&gt; b.f res0: String = Object B </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload