如何从执行转换的不可变值类型中抽象出来?
我想在 Modifier 的实现中封装真实类型的不可变解决方案对象,但找不到避免向下转型的方法。如何编写独立于解决方案类型的侦听器而不使它们具有类型参数?
以下代码说明,如果侦听器不知道解决方案的具体类型,则向下转型是不可避免的。
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
}
I want to incapsulate real type of immutable Solution object in implementation of Modifier but can’t find a way to avoid downcasts. How can I write Listeners independent on type of Solution without making them have a type parameter?
The following code illustrates that downcasts are unvoidable if Listener is unaware about concrete type of Solution.
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题中已经存在一个可能的答案 - 您可以使用抽象类型。
这是一个可能对您有帮助的示例:
One possible answer is already in your question - you can use abstract types.
Here is an example that may help you: