5

可能重复:
强制类型差异

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

编辑

下面的评论指向一个现有的问答,答案似乎是(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 <: B或者A >: B,还会是这样A =!= B吗?如果不是,是否可以修改解决方案,如果A =!= B不是这种情况,A <: B或者A >: B

4

1 回答 1

13

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 会话,

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]
                        ^
于 2012-08-27T09:33:33.663 回答