是否可以使用隐式证据来强制抽象类型之间的静态类型兼容性? [英] Is it possible to use implicit evidence to force static type compatibility between abstract types?

查看:26
本文介绍了是否可以使用隐式证据来强制抽象类型之间的静态类型兼容性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下特征:

trait A {
  type B
  def +(a:A):A
}

我使用抽象类型是因为我不想每次需要 A 时都在类型签名中拖动 B.是否仍然可以向 + 方法添加任何隐式证据(使用 =:=、<:< 等),以便编译器仍然可以强制接受具有相同 B 的 a:A?

I use an abstract type because I don't want to drag around the B in the type signature everytime I need an A. Is it still possible to add any implicit evidence (using =:=,<:<, etc.) to the + method so that the compiler can still enforce acceptance of a:A's with identical B's?

我的第一反应是拒绝,但之前 scala 给我带来了惊喜.任何帮助,将不胜感激.

My first instinct is to say no, but scala has pleasantly surprised me before. Any help would be appreciated.

推荐答案

不需要隐性证据...你可以使用显式细化,

No need for implicit evidence ... you can use an explicit refinement,

trait A {
  self =>
  type Self = A { type B = self.B }
  type B
  def +(a : Self) : Self
}

(注意使用 self 类型注释为外部this"提供别名,允许在类型 Self 的定义中区分定义的和定义的 B).

(note the use of a self type annotation to provide an alias for the outer 'this' allowing the defined and defining B's to be distinguished in the definition of type Self).

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

这篇关于是否可以使用隐式证据来强制抽象类型之间的静态类型兼容性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆