scala - Referencing vals in method returning new trait instance inside trait -


in following, have trouble referencing trait's offset value within + method (line 4).

as written this.offset zero. want offset lhs of + operation.

how should done?

trait side {   val offset: int // <- want refer   def +(side: side) = new object side {     val offset: int = this.offset + side.offset // instead `this.offset` 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 

the following works because side.this not refer anonymous class under construction.

anonymity has privileges.

scala> :pa // entering paste mode (ctrl-d finish)  trait side {   val offset: int   def +(side: side) = new side {     val offset = side.this.offset + side.offset   } }  // exiting paste mode, interpreting.  defined trait side  scala> new side { val offset = 1 } res0: side = $anon$1@7e070e85  scala> new side { val offset = 2 } res1: side = $anon$1@5f701cd1  scala> res0+res1 res2: side = side$$anon$1@188ef927  scala> .offset res3: int = 3 

first guess, thinking shadowing problem:

scala> :pa // entering paste mode (ctrl-d finish)  trait side {   val offset: int   def +(side: side) = new {     val offset = side.this.offset + side.offset   } side }  // exiting paste mode, interpreting.  defined trait side  scala> new side { val offset = 1 } res5: side = $anon$1@3fa76a13  scala> new side { val offset = 2 } res6: side = $anon$1@465fb2a5  scala> res5+res6 res7: side = side$$anon$1@7e84d99c  scala> .offset res8: int = 3 

ha. night , luck.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -