考虑以下:
object Main
{
case class Foo(bar: Int) extends FooList {
val self: List[Foo] = this :: Nil
}
abstract class FooList {
val self: List[Foo]
def ~(that: Foo) = { val list = self :+ that; new FooList { val self = list } }
}
def main(args: Array[String]): Unit = {
val foo = Foo(1) ~ Foo(2) ~ Foo(3)
println(foo.self)
}
}
Run Code Online (Sandbox Code Playgroud)
这行可以:
{ val list = self :+ that; new FooList { val self = list } }
Run Code Online (Sandbox Code Playgroud)
以任何方式简化?我想写一些类似的东西:
new FooList { val self = this.self :+ that } // won't compile
Run Code Online (Sandbox Code Playgroud)
似乎可以归结为能够引用具有相同名称的不同范围的标识符.那有什么机制吗?
ped*_*rla 13
这解决了范围问题.如果我理解正确,那就是你想要的.
abstract class FooList { outer =>
val self: List[Foo]
def ~(that: Foo) = { new FooList { val self = outer.self :+ that } }
}
Run Code Online (Sandbox Code Playgroud)
答:是的.自我类型也可以用作外部范围的别名.
| 归档时间: |
|
| 查看次数: |
365 次 |
| 最近记录: |