Wednesday, 15 February 2012

scala - Referring to the type being defined in type parameters -



scala - Referring to the type being defined in type parameters -

i'm trying come type safe messaging system. right best i've come this:

trait component trait message[from <: component, -to <: handler[from]] trait handler[from <: component]{ type messagetype <: message[from, this.type] def handle(message: messagetype): unit; }

what i'd more this:

trait component trait message[from <: component, -to <: handler[from]] trait handler[from <: component, messagetype <: message[from, this.type]]{ def handle(message: messagetype): unit; }

but compiler complains using this.type in type parameters. there way me refer type i'm defining in type parameters can utilize syntax i'd like?

it's possible type scheme want i'd utilize syntax like.

--edit--

i think i've found solution.

trait component trait message[from <: component, <: handler[from, to, messagetype], messagetype <: message[from, to, messagetype]] trait handler[from <: component, <: handler[from, to, messagetype], messagetype <: message[from, to, messagetype]]{ def handle(message: messagetype ): unit; }

a bit more verbose in type parameters works well.

i don't think need messagetype in type parameters accomplish want. instead create messagetype equal message[from, this.type].

trait handler[from <: component] { type messagetype = message[from, this.type] def handle(message: messagetype): unit; }

consider making message covariant in first parameter.

note this.type not refer type defining. this.type type has single value: this. this doesn't exist outside trait body, , hence cannot used in type parameters. if need refer type trait mixed into, need f-bounded polymorphism.

scala generics types

No comments:

Post a Comment