加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

oop – 限制可能实现Trait的类型

发布时间:2020-12-14 16:29:51 所属栏目:大数据 来源:网络整理
导读:是否可以限制可以实现特征的类型?比方说,例如我有一个类型 interface Something { void foo() } 和一个特点 trait SomethingAbility { void bar() { println "bar" }} 有没有办法我只能允许特性由Something类实现,例如 // OKclass SomethingImpl implements
是否可以限制可以实现特征的类型?比方说,例如我有一个类型

interface Something {
  void foo() 
}

和一个特点

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

有没有办法我只能允许特性由Something类实现,例如

// 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()
}

这意味着除非该类还提供了foo()方法,否则该类不能实现该特性,但这与类型为Something的类不同

解决方法

我认为你要找的是@Selftype,见 http://docs.groovy-lang.org/docs/latest/html/gapi/groovy/transform/SelfType.html
基本上它说明了使用这个特性的类必须实现什么.所以

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读