作为自身列表的类的模式 [英] Pattern for a class that is a list of itself

查看:37
本文介绍了作为自身列表的类的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下事项:

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

以任何方式简化?我想写一些类似的东西:

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.

这篇关于作为自身列表的类的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆