gpt4 book ai didi

scala - scala 中类型不等式的类型约束

转载 作者:行者123 更新时间:2023-12-02 04:39:12 24 4
gpt4 key购买 nike

Possible Duplicate:
Enforce type difference

由于 scala 中存在强制相等的广义类型约束 =:= ,是否有一个强制类型“不等于”的方法?基本上!=但对于类型?

编辑

下面的评论指向现有的 Q&A答案似乎是(1)不,它不在标准库中(2)是的,可以定义一个。

所以我会修改我的问题,因为我看到答案后想到了一个想法。

鉴于现有的解决方案:

sealed class =!=[A,B]

trait LowerPriorityImplicits {
implicit def equal[A]: =!=[A, A] = sys.error("should not be called")
}
object =!= extends LowerPriorityImplicits {
implicit def nequal[A,B](implicit same: A =:= B = null): =!=[A,B] =
if (same != null) sys.error("should not be called explicitly with same type")
else new =!=[A,B]
}

case class Foo[A,B](a: A, b: B)(implicit e: A =!= B)

如果A <: BA >: B ,还会是A =!= B吗? ?如果不是,是否可以修改解决方案,使得 A =!= B那么情况就不是 A <: BA >: B

最佳答案

shapeless定义类型运算符A <:!< B (意味着 A 不是 B 的子类型)使用与严格类型不等式相同的隐式歧义技巧,

trait <:!<[A, B]

implicit def nsub[A, B] : A <:!< B = new <:!<[A, B] {}
implicit def nsubAmbig1[A, B >: A] : A <:!< B = sys.error("Unexpected call")
implicit def nsubAmbig2[A, B >: A] : A <:!< B = sys.error("Unexpected call")

示例 REPL session ,

scala> import shapeless.TypeOperators._
import shapeless.TypeOperators._

scala> implicitly[Int <:!< String]
res0: shapeless.TypeOperators.<:!<[Int,String] =
shapeless.TypeOperators$$anon$2@200fde5c

scala> implicitly[Int <:!< Int]
<console>:11: error: ambiguous implicit values:
both method nsubAmbig1 in object TypeOperators of type
[A, B >: A]=> shapeless.TypeOperators.<:!<[A,B]
and method nsubAmbig2 in object TypeOperators of type
[A, B >: A]=> shapeless.TypeOperators.<:!<[A,B]
match expected type shapeless.TypeOperators.<:!<[Int,Int]
implicitly[Int <:!< Int]
^

scala> class Foo ; class Bar extends Foo
defined class Foo
defined class Bar

scala> implicitly[Foo <:!< Bar]
res2: shapeless.TypeOperators.<:!<[Foo,Bar] =
shapeless.TypeOperators$$anon$2@871f548

scala> implicitly[Bar <:!< Foo]
<console>:13: error: ambiguous implicit values:
both method nsubAmbig1 in object TypeOperators of type
[A, B >: A]=> shapeless.TypeOperators.<:!<[A,B]
and method nsubAmbig2 in object TypeOperators of type
[A, B >: A]=> shapeless.TypeOperators.<:!<[A,B]
match expected type shapeless.TypeOperators.<:!<[Bar,Foo]
implicitly[Bar <:!< Foo]
^

关于scala - scala 中类型不等式的类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135293/

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