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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With