gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:10:18 25 4
gpt4 key购买 nike

假设有以下特征:

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

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

我的第一 react 是拒绝,但 scala 之前曾让我惊喜。任何帮助,将不胜感激。

最佳答案

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

trait A {
self =>
type Self = A { type B = self.B }
type B
def +(a : Self) : 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

关于scala - 是否可以使用隐式证据来强制抽象类型之间的静态类型兼容性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5909890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com