开发者

Pattern for a class that is a list of itself

Consider the following:

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 } }
  }

  d开发者_如何学运维ef main(args: Array[String]): Unit = {
    val foo = Foo(1) ~ Foo(2) ~ Foo(3)
    println(foo.self)
 }
}

Could this line:

{ val list = self :+ that; new FooList { val self = list } }

be simplified in any way? I'd like to write something like:

new FooList { val self = this.self :+ that }   // won't compile

It seems to boil down to being able to refer to differently-scoped identifiers that has the same name. Is there any mechanism for that?


This solves the scoping issue. If I understand correctly that's what you want.

abstract class FooList { outer =>
  val self: List[Foo]
  def ~(that: Foo) = { new FooList { val self = outer.self :+ that } }
}

Answer: yes. Self-types can also be used as aliases to outer scopes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜