In Scala you must be careful with parameters when creating classes or you can get strange results.
class Parent(i: Int) { def iDef = i val iVal = i lazy val iLazy = i } class Child(val i: Int) extends Parent(i+10) val c = new Child(1) c.iLazy // Int = 11 c.iVal // Int = 11 c.iDef // Int = 11 c.i // Int = 1 Ops!
Child has different values for the same i? Lets try with val in the parent
class Parent(val i: Int) class Child(i: Int) extends Parent(i+10) { val childi = i } val c = new Child(1) c.i // Int = 11 c.childi // Int = 1
Don't confuse parent and child parameters! There are two, one in Parent and one in Child.
Maybe that's not what you want. So, why not define both as val and override in Child?
class Parent(val i: Int) { def iDef = i val iVal = i lazy val iLazy = i } class Child(override val i: Int) extends Parent(i+10) val c = new Child(1) c.iLazy // Int = 1 c.iVal // Int = 11 Hmmmm... ? c.iDef // Int = 1 c.i // Int = 1Oh, this is weird... Even with override I have two different values!
Be careful with construction order in classes. The problem is you made a copy in the parent constructor, which it was created before the child constructor.
No hay comentarios:
Publicar un comentario