0

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).

1 Answer 1

5

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) 
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, so basically I cannot do that. Thought there is some hack though through overriding things in Predef or something but haven't seen any operators there. Thx for the clarification, senia!
@rlegendi: there are no operators in scala. + is the method of Int: (1).+(2). It has nothing with Predef.
Can you prove in your example that multiplication happened, instead of addition? ;-)
@Jean-PhilippePellet: 2*2 is 4, so there should be no doubt it was multiplication. Yes, I've failed with example. =)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.