通常,這只是用重載方法完成的。然後調用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
}
}
來源
2012-08-10 02:00:35
dhg