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

  def main(args: Array[String]): Unit = {
    val foo = Foo(1) ~ Foo(2) ~ Foo(3)

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.

Need Your Help

FreeTDS not respecting freetds.conf and odbc.ini

sql-server ubuntu odbc freetds unixodbc

I have a problem, FreeTDS keep connecting using version 4.2 even if I set to 8.0 in these settings

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.