scala – 是否可以从self type调用重写方法?
考虑这个:
class Foo { def foo = "foo" } trait Bar { self: Foo => override def foo = "bar" } 我惊喜地发现这是可能的,并按预期工作: new Foo with Bar foo 返回“bar”.问题是Bar.foo是否可以调用Foo.foo,就像在“普通”继承情况下经常会做的一样.覆盖def foo = super.foo“bar”不起作用(说“foo不是AnyRef的成员”),也不会覆盖def foo = self.foo“bar”(它最终只是调用自身,并导致无限大递归). 这是不可能的吗? 解决方法
不可以从自己的类型调用重写方法.
首先,特征栏不是Foo类的继承者,所以不可能使用super.foo. 其次,也不可能使用self.foo,因为自己实际上是与Foo类型的Bar.可以通过在typer后打印程序来显示: $scalac -Xprint:typer test.scala [[syntax trees at end of typer]] // test.scala package <empty> { class Foo extends scala.AnyRef { def <init>(): Foo = { Foo.super.<init>(); () }; def foo: String = "foo" }; abstract trait Bar extends scala.AnyRef { self: Bar with Foo => def /*Bar*/$init$(): Unit = { () }; override def foo: String = "bar" }; class FooBar extends Foo with Bar { def <init>(): FooBar = { FooBar.super.<init>(); () } }; object TestApp extends scala.AnyRef { def <init>(): TestApp.type = { TestApp.super.<init>(); () }; def main(args: Array[String]): Unit = { val a: FooBar = new FooBar(); scala.this.Predef.println(a.foo) } } } 所以用self.foo,你试图访问trait Bar的方法foo.这种行为符合Scala Specification(PDF):
可以使用反射来访问该方法,但我认为这不是您要查找的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |