Scala type projection -
i have collection of models, each of exposes next(...) method moves model forward discrete step. each next() method has parameter given abstract type t.
i want able wrap each model class, wrapper inherit type t (which different each model), provide additional logic. trivial letting wrapper extend model, not feasible internal logic of actual model implementations.
my solution use type projections so:
trait model { type t // works fine when concrete implementation, cannot overridden def next(input : t) = println(input) } abstract class parent { type s <: model type t = s#t val model : s def next(input : t) = model.next(input) }
this fails compiler error: type mismatch; found : input.type (with underlying type parent.this.t) required: parent.this.model.t
note in concrete implementation of parent, parent.this.t should equal parent.this.model.t.
so far workaround abandon using type system, , creating unique parent classes each model (ie duplicating of other logic parent may expose). correct way this?
credits go @senia. setting type t = model.t
works fine:
abstract class parent { type s <: model type t = model.t val model : s def next(input : t) = model.next(input) } class simpleparent[gt <: model](val model: gt) extends parent { type s = gt } trait stringmodel extends model { type t = string } trait intmodel extends model { type t = int } object test { new simpleparent(new stringmodel {}) new simpleparent(new intmodel {}) }
have @ here, see why type t = s#t
doesn't work. (short version: have model.type <: s
, s#t
not concrete, hence s#t
incompatible model.t
).
Comments
Post a Comment