通常,这将通过重载方法来完成。然后在调用 on 方法时Bar
,他们可以传入一两件事:
abstract class Foo {
def doSomething(a: Int): Int
def doSomething(a: Int, b: Int): Int
}
class Bar extends Foo {
def doSomething(a: Int): Int = a
def doSomething(a: Int, b: Int): Int = a * b
}
或者,使用默认参数(仍然允许您这样做new Bar().doSomething(5)
)
abstract class Foo {
def doSomething(a: Int, b: Int = 1): Int
}
class Bar extends Foo {
def doSomething(a: Int, b: Int): Int = a * b
}
但听起来您想以一种始终调用相同Foo
方法的方式执行此操作,因此在这种情况下,您可以对参数执行多态性:
trait Thing
case class Thing1(a: Int) extends Thing
case class Thing2(a: Int, b: Int) extends Thing
abstract class Foo {
def doSomething(t: Thing): Int
}
class Bar extends Foo {
def doSomething(t: Thing): Int = t match {
case Thing1(a) => a
case Thing2(a, b) => a * b
}
}
或者,因为你只有两个选择,你可以用一个做同样的事情Either
:
abstract class Foo {
def doSomething(t: Either[Int, (Int, Int)]): Int
}
class Bar extends Foo {
def doSomething(t: Either[Int, (Int, Int)]): Int = t match {
case Left(a) => a
case Right((a, b)) => a * b
}
}