如何为抽象类中的方法提供参数,以便以后可以扩展参数?我将在下面举例说明一个简单的场景。
abstract class Car {
def drive(x: Driver)
}
abstract class Driver
case class DriverA(name: String) extends Driver
case class DriverB(name: String, age: Int) extends Driver
class Audi extends Car {
// each child class should have a more specific type for param "x"
def drive(x: DriverA) = { ... }
}
class BMW extends Car {
// each child class should have a more specific type for param "x"
def drive(x: DriverB) = { ... }
}
但这在Scala中不起作用:“错误:[..]方法参数类型必须完全匹配”
我也试过指定上限类型,就像这个def驱动[T<:Driver](x:T):Int,但仍然没有运气。似乎我错过了一些简单而明显的东西。
这样的设计有问题吗?
答案 0 :(得分:6)
您可以在scala中使用abstract type:
scala> :paste
// Entering paste mode (ctrl-D to finish)
abstract class Car {
type D <: Driver
def drive(x: D): Unit
}
abstract class Driver
case class DriverA(name: String) extends Driver
case class DriverB(name: String) extends Driver
class Audi extends Car {
type D = DriverA
def drive(x: DriverA): Unit = println(x.name)
}
// Exiting paste mode, now interpreting.
defined class Car
defined class Driver
defined class DriverA
defined class DriverB
defined class Audi
scala> new Audi().drive(DriverA("test"))
test
或者使用类型为参数化的类:
scala> :paste
// Entering paste mode (ctrl-D to finish)
abstract class Driver
case class DriverA(name: String) extends Driver
abstract class Car[D <: Driver] {
def drive(x: D): Unit
}
class Audi extends Car[DriverA] {
def drive(x: DriverA) = println(x.name)
}
// Exiting paste mode, now interpreting.
scala> new Audi().drive(DriverA("zzz"))
zzz