强制特征由Object实现

时间:2017-09-02 01:13:12

标签: scala object traits

如何强制scala中的特征只能被对象扩展(不是类,特征等)?

我有以下星座:

trait Outer { self: SomeOtherClass =>
  def member: Inner.type = Inner

  /* some other methods... */

  trait Inner { iself =>
    def parent: self.type = self
    /* other methods... */
  }
}

我的问题是:我如何强制内部特征必须由一个对象实现(如对象Inner extends Inner {...})?

我希望每个实现Outer的类都有一个内部对象,它携带一些状态+从内部获取内部的可能性,反之亦然。

致以最诚挚的问候,

约亨

编辑:

示例:

// compiles
class C extends Outer {
  object Inner extends Inner { ... }
}

// doesn't compile
class C extends Outer {
  class Inner extends Inner { ... }
}

1 个答案:

答案 0 :(得分:0)

使用Singleton自我类型:

trait Outer {
  def member: Inner
  /* other methods... */
  trait Inner { self: Singleton =>
    def parent: Outer.this.type = Outer.this
    /* other methods... */
  }
}

class OImpl extends Outer {
  // Note that OImpl's subclasses can't override member this way
  // You could also do private[this] object member0 extends Inner
  // and override lazy val member = member0 to restore overridability
  // The laziness of object and lazy val mean that member0 won't be created
  // if a subclass doesn't use it.
  override object member extends Inner {
    // ...
  }
  // ...
}