for*_*ran 16 generics recursion scala type-safety
有一个常见的Java习惯用法(Enum例如见过)来声明一个必须与实际派生类型匹配的泛型类型变量.
class Enum<E extends Enum<E>> {
...
}
Run Code Online (Sandbox Code Playgroud)
或者,如果需要更多通用参数:
abstract class Foo<T, Actual extends Foo<T, Actual>> {
//now we can refer to the actual type
abstract Actual copy();
}
class Concrete<T> extends Foo<T, Concrete<T>> {
Concrete<T> copy() {...}
}
Run Code Online (Sandbox Code Playgroud)
事情可以很快变得非常冗长,所以我想象Scala可能比上面例子的字面翻译更好.
有没有更优雅的方法来实现这一目标?
Ale*_*rlo 10
另一种方法是使用抽象类型成员:
trait Foo { self =>
type A <: Foo {type A = self.A}
}
Run Code Online (Sandbox Code Playgroud)
用你的例子:
trait Foo { self =>
type T
type Actual <: Foo {type T = self.T; type Actual = self.Actual}
}
trait Concrete extends Foo { self =>
type T
type Actual = Concrete {type T = self.T}
}
Run Code Online (Sandbox Code Playgroud)
虽然这种重新制定在特质/类声明方面并不是很好,但在使用特征/类时,它可能更加简洁.(据我所知,没有其他方法可以重新构造递归类型).