限制可能实现特征的类型

Restrict types that may implement a Trait

是否可以限制可以实现特征的类型?比如说,我有一个类型

interface Something {
  void foo() 
}

和一个特征

trait SomethingAbility {
  void bar()  {
    println "bar"
  }
}

有没有一种方法可以让我只允许 class 类型 Something 的 es 实现该特征,例如

// OK
class SomethingImpl implements Something, SomethingAbility {
  void foo() {
    println "foo"
  }
}

// error: this class should not be allowed to implement the trait
// because it's not a Something
class NotSomething implements SomethingAbility {
  void foo() {
    println "foo"
  }
}

一种选择是向特征添加抽象方法

trait SomethingAbility {
  void bar() {
    println "bar"
  }

  abstract void foo()
}

这意味着特征不能由 class 实现,除非 class 也提供了 foo() 方法,但这与class 属于 Something

类型

我想你要找的是@Selftype,见http://docs.groovy-lang.org/docs/latest/html/gapi/groovy/transform/SelfType.html 基本上它说明了使用此特征的 class 必须实现的内容。所以用

@SelfType(Something)
trait SomethingAbility {
   void bar()  {
     println "bar"
   }
}

你声明,任何使用此特征的 class 也必须实现接口 Something。例如,这可确保如果您静态编译特征并从接口 Something 调用方法,则编译不会失败。当然对于标准 Groovy 这不是必需的,因为鸭子打字。