0

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.

chrisf
  • 3
  • 1

1 Answers1

2

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
Community
  • 1
  • 1
senia
  • 37,745
  • 4
  • 88
  • 129
  • thank you. does it mean i cant define a method which is right associative and only takes 1 operand ( add3to myInt). Your method i also cant call " 3 addTo myInt"? – chrisf May 22 '13 at 12:17
  • @chrisf: 1) You could just define `def add3To(mi: MyInt) = i.x+3` and call it as `add3To(myInt)`. 2) You could add method `addTo(mi: MyInt)` to `Int` - see [`implicit class`](http://docs.scala-lang.org/sips/pending/implicit-classes.html). – senia May 22 '13 at 12:48