2012-08-27 130 views
4

可能重复:
Enforce type difference类型约束类型不等式

由于是一个广义类型约束强制执行阶=:=平等,是有一个强制执行“不等于”对于类型?基本上!=但类型?

编辑

评论下方指向现有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

+2

SO开发者应该*确实*修正他们的搜索错误,以便寻找'=!='实际上列出了这个问题。这个bug现在已经有4年了。 –

回答

11

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] = 
    [email protected] 

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] = 
    [email protected] 

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] 
         ^
+0

是否有必要让这种方法适用于更高级别的类型? 类似于 类型A [+ T] 含蓄地[A [T] <:!

+0

对不起,我的问题似乎并不是针对较高kinded类型,但是当您mixin trait {type A [+ T] = Iterable [T]}它管理编译 –

+0

http://stackoverflow.com/questions/23591466/scala-mixin-type-constraints-still-compiles –