2012-08-27 126 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 –