我想在Modifier的实现中封装真实类型的不可变Solution对象,但无法找到避免向下转换的方法。如何在不使其具有类型参数的情况下独立于解决方案类型编写侦听器?
以下代码说明如果Listener不了解具体类型的解决方案,那么向下转换是不可避免的。
trait Solution {} //Immutable abstact class
trait Listener(val modifier: Modifier) {
def onChange(iSolution: Solution): Solution
}
trait Modifier { //Implementations use different descendants of Solution
def addListener(listener: Listener)
def emptySolution: Solution
def transfrom1(iSolution: Solution): Solution //Downcast of argument can’t be avoided in implementations of these
def transfrom2(iSolution: Solution): Solution
}
class Listener1 extends Listener { //Should be independent from Solution concrete type. Current implentation meets this requirement by introducing downcasts in Modifier.
val modifier: Modifier
def onChange(iSolution: Solution) = modifier.transform1(modifier.transform2(iSolution)) // Some action involving solution transformations with modifier
}
答案 0 :(得分:4)
您的问题中已经有一个可能的答案 - 您可以使用抽象类型。
以下是一个可以帮助您的示例:
trait Solution {}
trait Listener {
val modifier: Modifier
def onChange(iSolution: modifier.solType): modifier.solType
}
trait Modifier {
type solType <: Solution
def addListener(listener: Listener)
def emptySolution: Solution
def transform1(iSolution: solType): solType
def transform2(iSolution: solType): solType
}
trait Listener1 extends Listener {
val modifier: Modifier
def onChange(iSolution: modifier.solType) = modifier.transform1(modifier.transform2(iSolution))
}