Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patterns for same method & same parameters but different parameter names in scala

Tags:

scala

I'd like to be able to do:

object AddOrSubtract {
  def apply(x: Int, adding: Int) = x + adding
  def apply(x: Int, subtracting: Int) = x - subtracting
}

AddOrSubtract(1, adding = 5) // should be 6
AddOrSubtract(1, subtracting = 5) // should be -4

But I get the error:

Error:(1331, 7) method apply is defined twice;
  the conflicting method apply was defined at line 1330:7
  def apply(x: Int, subtracting: Int) = x - subtracting

I understand that this is because the two methods have the same signatures. Is there some pattern for getting around this? The only thing I can think of is using an implicit to change the type of value, like:

object AddOrSubtract {
  implicit class AddInt(val x: Int)
  implicit class SubInt(val x: Int)

  def apply(x: Int, adding: AddInt) = x + adding.x
  def apply(x: Int, subtracting: SubInt) = x - subtracting.x

  def run(): Unit = {
    AddOrSubtract(1, adding = 5)
    AddOrSubtract(1, subtracting = 5)
  }
}

But I'm curious if there is any other less inelegant way of accomplishing this?

like image 967
marcprux Avatar asked Jun 13 '26 13:06

marcprux


2 Answers

Your example code may be over-simplified for your real-world use case. If so then this solution won't be applicable.

object AddOrSubtract {
  def apply(x: Int, adding: Int=0, subtracting: Int=0) = x + adding - subtracting
}

AddOrSubtract(1, adding = 5)      // res0: Int = 6
AddOrSubtract(1, subtracting = 5) // res1: Int = -4
like image 200
jwvh Avatar answered Jun 16 '26 08:06

jwvh


AFAIK there is no good solution. The only workaround I can imagine is

  object AddOrSubtract {
    def apply(x: Int, adding: Int = 0, subtracting: Int = 0) = 
      match (adding, subtracting) {
        case (0, 0) => throw Error("either adding or subtracting is required")
        case (x, 0) => x + adding
        case (0, x) => x - subtracting
       case (_, _) => throw Error("for now both adding and subtracting is not allowed")
   }

 AddOrSubtract(1, adding = 5) // should be 6
 AddOrSubtract(1, subtracting = 5) // should be -4

But it is far from perfect

like image 39
VMykyt Avatar answered Jun 16 '26 09:06

VMykyt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!