类的模式是其自身的列表

发布于 2024-10-06 04:39:46 字数 664 浏览 3 评论 0原文

考虑以下问题:

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

它似乎可以归结为能够引用具有相同名称的不同范围的标识符。有什么机制可以做到这一点吗?

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)
    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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏雨一样淡蓝的深情 2024-10-13 04:39:46

这解决了范围界定问题。如果我理解正确的话那就是你想要的。

abstract class FooList { outer =>
  val self: List[Foo]
  def ~(that: Foo) = { new FooList { val self = outer.self :+ 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文