Frage

i am learning scala ( like it! ) but there is something i dont understand. i read about right associative operand by method names ending with ":". Easy to understand but i wanted to define my own right associative function named add3To:.

I have a syntaxerror and dont know why:

case class MyInt(x : Int) {
   def add3 = x+3

   def add3To:= x+3 // dont understand whats wrong here
}

val myInt = MyInt(4)
println(myInt add3)  // working 
println(add3To myInt)  // not working

Maybe ( i am pretty sure) i did a dumb mistake! But i dont see it.

War es hilfreich?

Lösung

You should place an underscore between letters and punctuation characters in name. add3To_:, not add3To:.

Method should accept a single parameter: addTo_:(i: Int).

scala> case class MyInt(x : Int) {
     |    def addTo_:(i: Int): Int = x+i
     | }
defined class MyInt

scala> val myInt = MyInt(4)
myInt: MyInt = MyInt(4)

scala> 3 addTo_: myInt
res0: Int = 7
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top