Scala 类的模式,该类是其自身的列表
考虑以下几点:Scala 类的模式,该类是其自身的列表,scala,Scala,考虑以下几点: 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 } } }
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)
}
}
请问这句话:
{ val list = self :+ that; new FooList { val self = list } }
可以简化吗?我想写一些类似于:
new FooList { val self = this.self :+ that } // won't compile
它似乎可以归结为能够引用具有相同名称的不同范围的标识符。有什么机制吗?这解决了范围界定问题。如果我理解正确,那就是你想要的
abstract class FooList { outer =>
val self: List[Foo]
def ~(that: Foo) = { new FooList { val self = outer.self :+ that } }
}
回答:是。自类型也可以用作外部作用域的别名