Scala 中类型不等式的类型约束 [英] Type constraint for type inequality in scala
问题描述
可能的重复:
强制类型差异
既然在scala =:=
中有一个强制相等的通用类型约束,那么是否有一个对类型强制执行不等于"的约束?基本上 !=
但对于类型?
Since there is a generalized type constraint enforcing equality in scala =:=
, is there one that enforces "not equals" for types? Basically !=
but for types?
编辑
下面的评论指向现有的问答,答案似乎是 (1)不,它不在标准库中 (2) 是的,可以定义一个.
Comment below points to an existing Q&A and the answer seems to be that (1) no, it's not in the standard library (2) yes, it's possible to define one.
所以我会修改我的问题,因为我看到答案后想到了一个想法.
So I'll modify my question because of a thought that occurred to me after I saw the answer.
鉴于现有的解决方案:
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 <: B
或A >: B
,是否仍然是A =!= B
?如果不是,是否可以修改解决方案,如果 A =!= B
那么A <: B
或 A >;: B
?
If A <: B
or A >: B
, will it still be the case that A =!= B
? If not, is it possible to modify the solution such that if A =!= B
then it is not the case that A <: B
or A >: B
?
推荐答案
shapeless 定义了类型运算符 <代码>A <:!<B(意味着 A
不是 B
的子类型)使用与严格类型不等式相同的隐式歧义技巧,
shapeless defines the type operator A <:!< B
(meaning A
is not a subtype of B
) using the same implicit ambiguity trick that's used for strict type inequality,
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 会话,
Sample 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 中类型不等式的类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!