5

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)
}
Miles Sabin
  • 23,015
  • 6
  • 61
  • 95
Hugo Sereno Ferreira
  • 8,600
  • 7
  • 46
  • 92

1 Answers1

14

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 = ???
Miles Sabin
  • 23,015
  • 6
  • 61
  • 95