我希望能够做到:
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
但我收到错误:
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
据我所知,这是因为这两种方法具有相同的签名。是否有一些模式可以解决这个问题?我唯一能想到的是使用隐式来改变值的类型,例如:
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)
}
}
但我很好奇是否有其他不那么不优雅的方式来实现这个目标?
答案 0 :(得分:3)
您的示例代码可能会针对您的实际用例进行过度简化。如果是,则此解决方案将不适用。
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
答案 1 :(得分:2)
AFAIK没有好的解决方案。 我能想象的唯一解决方法是
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
但它远非完美