是否可以使用隐式证据来强制抽象类型之间的静态类型兼容性?

发布于 2024-11-05 07:36:23 字数 235 浏览 0 评论 0原文

假设以下特征:

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

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

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

Assume the following trait:

trait A {
  type B
  def +(a: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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戒ㄋ 2024-11-12 07:36:23

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

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

(注意使用 self 类型注释来为外部“this”提供别名,从而允许在 Self 类型的定义中区分已定义的 B 和正在定义的 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

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
}

(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 transcript,

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文