rlegendi
rlegendi

Reputation: 10606

Is it possible to override built-in operators in Scala?

This is rather a hypothetical question, but let's say I'd like to change the behaviour of + (or any other arithmetic operator) on Int within a scope, something like this (I know it is something crazy and is something I'd try to avoid in general, but I find it interesting):

object MySillyStuff extends App {
  def +(a: Int, b: Int) = a*b;

  println(1+2)
}

Is that possible this way, or I'm only able to overload operators through implicit conversions with a new type? (I.e., I have to explicitly create 1 as a member of that new type and use implicit conversion of 2 for that specific type).

Upvotes: 0

Views: 807

Answers (1)

senia
senia

Reputation: 38045

Note that there are no operators in scala. In the question + is the method of Int: (1).+(2).

The only way to override an existing method is inheritance with override keyword.

Implicit class allows you to add a new method, but not to override the method that already is there.

You could wrap your class without overhead using value classes like this:

case class StrangeInt(val i: Int) extends AnyVal {
  def +(that: Int): StrangeInt = StrangeInt(i*that)
}

val i = StrangeInt(3)
println(i+3)
// StrangeInt(9)

Upvotes: 5

Related Questions