How to abstract from type of immutable value performing its transformations?
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) {
开发者_StackOverflow 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
}
One possible answer is already in your question - you can use abstract types.
Here is an example that may help you:
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))
}
精彩评论