- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
how to convert parameterized types to abstract types
Sat, 2009-02-14, 00:13
Hi,
How would I convert the following to use abstract types instead of
parameterized types?
trait Parent[P <: Parent[P, C], C <: Child[C, P]] {
self: P =>
def setParent(item:C) = {
item.parent = this
}
}
trait Child[C <: Child[C, P], P <: Parent[P, C]] {
self: C =>
var parent: P = _
}
The closest I've come is the following:
trait Parent {
type T >: this.type <: Parent
type C <: Child { type P = T }
def setParent(item:C) = {
item.parent = this // This fails
}
}
trait Child {
type T >: this.type <: Child
type P <: Parent { type C = T }
var parent:P
}
Thanks,
Scott
Scott Rader wrote:
> Hi,
>
> How would I convert the following to use abstract types instead of
> parameterized types?
>
> trait Parent[P <: Parent[P, C], C <: Child[C, P]] {
> self: P =>
>
> def setParent(item:C) = {
> item.parent = this
> }
> }
>
> trait Child[C <: Child[C, P], P <: Parent[P, C]] {
> self: C =>
> var parent: P = _
> }
>
> The closest I've come is the following:
>
> trait Parent {
> type T >: this.type <: Parent
> type C <: Child { type P = T }
>
> def setParent(item:C) = {
> item.parent = this // This fails
> }
> }
>
> trait Child {
> type T >: this.type <: Child
> type P <: Parent { type C = T }
>
> var parent:P
> }
>
> Thanks,
>
> Scott
>
We can use "Child { type P = self.P }" to avoid needing distinct names
like T.
Can somebody who has working Trac access please add the following as a
much simpler example of
http://scala-webapps.epfl.ch/bugtracking/bugs/displayItem.do?id=1161
trait Child {
type P
var parent: P = _
}
trait Parent { self =>
type P >: this.type
def setParent(item: Child { type P = self.P } ) {
item.parent = this
// ^
// error: type mismatch; found Parent, required item.P
// succeeds: item.parent = (this: P)
}
}
We can hand-hold the compiler by using "(this: P)" instead of "this" and
the compile succeeds.