Aladdin - Scala Bugtracking
[#1078] project: compiler priority: low category: bug
submitter assigned to status date submitted
Nikolay Martin noise 2007-05-01 13:00:56.0
subject [contrib #450] this.asInstanceOf[this class].instance_variable uses base class
code
In this thread

http://thread.gmane.org/gmane.comp.lang.scala/4918

with this code

class Base(var base : int)
{
   def getBase() = {
     System.out.println("Base.getBase " + base)
     base
   }
}

class Derived1(base : int) extends Base(200)
{
   override def getBase() = {
     val s = this.base
     System.out.println("Derived1.getBase " + s)
     s
   }
}

class Derived2(base : int) extends Base(200)
{
   override def getBase() = {
     val s = this.asInstanceOf[Base].base
     System.out.println("Derived2.getBase " + s)
     s
   }
}

class Derived3(base : int) extends Base(200)
{
   override def getBase() = {
     val s = this.asInstanceOf[Derived3].base
     System.out.println("Derived3.getBase " + s)
     s
   }
}

object Test extends Application
{
   new Base(100).getBase()
   new Derived1(100).getBase()
   new Derived2(100).getBase()
   new Derived3(100).getBase()
}

Martin Odersky states that 

http://thread.gmane.org/gmane.comp.lang.scala/4918/focus=4921

"The reason it does not do this is the following: base in Derived1 is a
private field. As such it does not override the base field in class
Base. Instead, we have a case of shadowing. So if the static type of
the receiver is Derived1, you get its field, but if the static type is
Base, you get the hidden field. Java is not different there, I
believe."

This suggests that the output for Derived3 is incorrect, since
this.asInstanceOf[Derived3] is statically a Derived3, but it's
returning the base class field.

http://thread.gmane.org/gmane.comp.lang.scala/4918/focus=4922

Regards,
Blair
what happened
Output is

Base.getBase 100
Derived1.getBase 100
Derived2.getBase 200
Derived3.getBase 200
what expected Expecting Base.getBase 100 Derived1.getBase 100 Derived2.getBase 200 Derived3.getBase 100
[back to overview]
Changes of this bug report
Nikolay  edited on  2007-05-01 13:05:06.0
contribution #450
Martin  edited on  2007-05-29 19:25:21.0
My previous explanation was incomplete. There are two base members: an object-private parameter in each class and the inherited base field. The object-private parameter is accessible only if the prefix is absent or is equal to `this.'. It shadows the inheroited field wheere it is accessible. Since `base' is inaccessible in Derived2/3, the inherited base field is picked instead.