Scala中类型不相等的证据

时间:2014-07-01 21:23:45

标签: scala types shapeless implicits

有没有办法约束一个方法,只有当两个类型被证明相等时才有意义?

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

1 个答案:

答案 0 :(得分:12)

是。来自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 = ???