我想有一个密封的特征,它有一个声明的方法,返回扩展特征的实际类.我应该使用抽象类型,参数类型还是有任何其他好方法来解决这个问题?
sealed trait Foo {
type T
def doit(other: T): T
}
Run Code Online (Sandbox Code Playgroud)
要么
sealed trait Foo[T] {
def doit(other: T): T
}
Run Code Online (Sandbox Code Playgroud)
请注意,在此示例中T必须是子类型Foo.如果我这样做,类型信息会重复:
case class Bar(name: String) extends Foo[Bar] {
def doit(other: Bar): Bar = ...
}
Run Code Online (Sandbox Code Playgroud)
doit您可以通过让您的方法返回工厂函数来减少重复:
trait Foo[T] {
self: T =>
def doit: T => T
}
case class Bar(name: String) extends Foo[Bar] {
// note: types omitted
def doit = { other => Bar(name + other.name) }
}
Run Code Online (Sandbox Code Playgroud)
不可能对抽象类型执行相同的操作:
trait Foo {
self: T => // won't compile because T isn't defined yet
type T
def doit: T => T
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3161 次 |
| 最近记录: |