scala – 是否可以使用隐式证据来强制抽象类型之间的静态类型兼
发布时间:2020-12-16 08:53:41  所属栏目:安全  来源:网络整理 
            导读:假设以下特征: trait A { type B def +(a:A):A} 我使用抽象类型,因为每次我需要A时,我不想在类型签名中拖动B. 是否仍然可以向方法添加任何隐式证据(使用=:=,:等等),以便编译器仍然可以强制接受a:具有相同B的A? 我的第一直觉是说不,但斯卡拉以前让我惊喜
                
                
                
            | 
 假设以下特征: 
  
  
  trait A {
  type B
  def +(a:A):A
}我使用抽象类型,因为每次我需要A时,我不想在类型签名中拖动B. 解决方法
 无需隐式证据……您可以使用显式细化, 
  
  trait A {
  self =>
  type Self = A { type B = self.B }
  type B
  def +(a : Self) : Self
}(注意使用自我类型注释为外部’this’提供别名,允许在Self类型的定义中区分定义和定义的B). REPL成绩单, scala> trait A { self => type Self = A { type B = self.B } ; type B ; def +(a : Self) : Self }
defined trait A
scala> val ai = new A { type B = Int ; def +(a : Self) : Self = this }
ai: java.lang.Object with A{type B = Int} = $anon$1@67f797
scala> val ad = new A { type B = Double ; def +(a : Self) : Self = this }
ad: java.lang.Object with A{type B = Double} = $anon$1@7cb66a
scala> ai + ai
res0: ai.Self = $anon$1@67f797
scala> ad + ad 
res1: ad.Self = $anon$1@7cb66a
scala> ai + ad
<console>:9: error: type mismatch;
 found   : ab.type (with underlying type java.lang.Object with A{type B = Double})
 required: ai.Self
       ai + ab(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
