boaz
boaz

Reputation: 900

Scala- operator overloading for an Int

I'm new to Scala and I was wandering if there is an option to overload the Int plus. just for example, lets say that I want 1+2 to return 1*2. can I do something like this?

Upvotes: 1

Views: 740

Answers (1)

0__
0__

Reputation: 67330

You cannot overload the methods of a final class such as Int. You can only add new (extension) methods:

implicit class IntPlusPlus(private val a: Int) extends AnyVal {
  def ++ (b: Int): Int = a * b
}

assert(2 ++ 3 == 6)

Or if you want to use + for something different, introduce a different type:

class MyInt(val self: Int) extends Proxy {
  def + (b: MyInt): MyInt = new MyInt(self * b.self)
}

assert(new MyInt(2) + new MyInt(3) == new MyInt(6))

Upvotes: 5

Related Questions