类的模式是其自身的列表
考虑以下问题:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这解决了范围界定问题。如果我理解正确的话那就是你想要的。
答案:是。自类型也可以用作外部作用域的别名。
This solves the scoping issue. If I understand correctly that's what you want.
Answer: yes. Self-types can also be used as aliases to outer scopes.