2014-07-01 29 views
4

有沒有什麼辦法來約束一個方法,只有在兩種類型都被證明是而不是是相等時纔有意義?Scala中類型不相等的證據

trait Something[A, B] { 
    // I can only be called if type A is the same as type B 
    def ifEqual(implicit ev: A =:= B) 

    // Now I cannot be called if type A is proven to be the same as type B 
    def ifNotEqual(implicit ev: A ??? B) 
} 

回答

10

是的。來自shapeless

// Type inequalities 
trait =:!=[A, B] 

implicit def neq[A, B] : A =:!= B = new =:!=[A, B] {} 
implicit def neqAmbig1[A] : A =:!= A = ??? 
implicit def neqAmbig2[A] : A =:!= A = ??? 
+0

一如既往,驚人的型福! –

+3

這一定是重複的,除非是很酷的Miles邁過來回答它。就像馬歇爾麥克盧漢出現在電影裏時那樣,安妮霍爾的那個場景。 「如果生活只是這樣!」 –

+0

確定重複。請參閱http://stackoverflow.com/questions/6909053/enforce-type-difference。 –