0

It just makes sense that =:= should be commutative: A =:= B implies B =:= A. I was wondering if there is a way to make the scala understand this. To elaborate, if I provide the scala with

implicit def typeEqCommutes[A,B](ev: A=:=B): B=:=A = ev.asInstanceOf[B=:=A]
then is there a way so the following would compile:
    class Pair[T, S](var first: T, var second: S) {
    def swap(implicit ev: T =:= S) {
      val temp = first
      first = second //error: type mismatch; found: S required: T

      second = temp
    }
  }
Ashkan Kh. Nazary
  • 21,844
  • 13
  • 44
  • 68

1 Answers1

0

Well, it may not exactly be what you are asking for, but you could try being a bit more explicitly implicit:

class Pair[T, S](var first: T, var second: S) {
  def swap(implicit ev: T =:= S, commutative: S =:= T) {
    val temp = first
    first = commutative(second)

    second = ev(temp)
  }
}

finding evidence for S =:= T should not be a problem for the compiler as type sameness as proven by =:= should indeed be commutative.

If you want to do it with an implicit conversion you would have to do it like that:

implicit def commutativity[A, B](in: B)(implicit ev: A =:= B): A = {
  in.asInstanceOf[A]
}

class Pair[T, S](var first: T, var second: S) {
  def swap(implicit ev: T =:= S) {
    val temp = first
    first = second

    second = ev(temp)
  }
}

Though, imho, not needing to use asInstanceOf is always preferable.

Sascha Kolberg
  • 7,092
  • 1
  • 31
  • 37