Saturday, 10 August 2013

Referencing vals in method returning new trait instance inside trait

Referencing vals in method returning new trait instance inside trait

In the following, I have trouble referencing the trait's offset value
within the + method (line 4).
As it is currently written this.offset is always zero. What I want is the
offset from the LHS of the + operation.
How should it be done?
trait Side {
val offset: Int // <- I want to refer to this
def +(side: Side) = new Object with Side {
val offset: Int = this.offset + side.offset // but instead
`this.offset` is 0
}
}
case object Left extends Side {
val offset = -1
}
case object Right extends Side {
val offset = 1
}
(Left + Right).offset // -> (0 + 1) -> 1
(Right + Left).offset // -> (0 + -1) -> -1

No comments:

Post a Comment