Jas*_*ond 4 type-systems scala
可能重复:
强制类型差异
由于存在一个在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)
Run Code Online (Sandbox Code Playgroud)
如果A <: B或者A >: B,情况仍然如此A =!= B?如果没有,是否有可能修改的解决方案,例如,如果A =!= B那么它是不是这样说A <: B还是A >: B?
Mil*_*bin 12
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")
Run Code Online (Sandbox Code Playgroud)
示例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]
^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1925 次 |
| 最近记录: |