我用一个抽象方法和几个具体方法定义了一个Super[A]
特征,其中许多方法只是创建了一个带有一些变化的新对象实例。这是一个例子:
trait Super[A] { self =>
def abstractMethod: A
def map[B](f: A => B): Super[B] = new Super[B] {
def abstractMethod = f(self.get)
}
}
我现在想构建一些继承自Super[A]
的类,而不更改每个具体方法的返回类型。
实现这样一个结果的最常用方法是什么?
答案 0 :(得分:0)
你说你不想改变你的具体方法的返回类型,所以在这个例子中映射...我没有看到你必须改变其返回类型的任何理由。一个简单的例子。
注意:.get没有定义,所以我在.map中使用了.abstractMethod
trait Super[A] { self =>
def abstractMethod: A
def map[B](f: A => B) = new Super[B] {
def abstractMethod = f(self.abstractMethod)
}
}
几个班级
class X(val n: Int) extends Super[X] {
def abstractMethod = this
def toY = new Y(n)
}
class Y(val n: Int) extends Super[Y] {
def abstractMethod = this
def toX = new X(n)
}
按预期工作
val x: X = new X(999)
val y: Y = x.map(_.toY).abstractMethod
val x2: X = y.map(_.toX).abstractMethod
val sup_x: Super[X] = x.map(_.abstractMethod)
val sup_y: Super[Y] = x.map(_.toY)
val sup_y2: Super[Y] = sup_x.map(_.toY)
val sup_x2: Super[X] = sup_y.map(_.toX)