Search code examples
scalatypesshapelessimplicits

Evidence that types are not equal in Scala


Is there any way to constraint a method so that it only makes sense if two types are proved not to be equal?

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)
}

Solution

  • Yes. From 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 = ???