1

Assume code:

class A
class B

class Something {
  def method(arg: A) = ???
  def method(arg: B) = ???
}

class C

object C {
  implicit def ctoa(c: C): A = ???
  implicit def ctob(c: C): B = ???
}

Additionally:

  • Classes A, B and Something and their companions cannot be modified
  • There must be an implicit conversion from C to A and from C to B, their priority doesn't matter
  • Other than that, class C and its companion can be freely modified
  • Of course, more types, implicits etc. can be added

Now, is there a way to make this compile:

(new Something).method(new C)

?

ghik
  • 10,111
  • 1
  • 34
  • 45

1 Answers1

2

I know this isn't what you were looking for, but I don't see any way to do it except to get one of those implicits into another scope.

class A
class B

class Something {
  def method(arg: A) = println("method(A)")
  def method(arg: B) = println("method(B)")
}

class C

object C {
  implicit def ctoa(c: C): A = new A
}

object X {
  implicit def ctob(c: C): B = new B
}

Then you get:

scala> (new Something).method(new C)
method(A)

Otherwise, you're trying to violate the Non-Ambiguity Rule: "An implicit conversion is only inserted if there is no other possible conversion to insert." See Programming in Scala.

Matt Malone
  • 411
  • 4
  • 23
  • There is a way to control priority of implicit conversions in case of ambiguity (e.g. by putting low priority implicits into a superclass/trait) but I don't know why it doesn't work in this case. – ghik Nov 21 '13 at 20:32
  • What's your source for that superclass/trait thing? Daniel Sobral did a post about implicit priorities. http://stackoverflow.com/questions/5598085/where-does-scala-look-for-implicits C.ctoa and C.ctob are in the same compilation unit, so I think the precedence groups described by Daniel don't come into play. – Matt Malone Nov 21 '13 at 23:00
  • http://stackoverflow.com/questions/1886953/is-there-a-way-to-control-which-implicit-conversion-will-be-the-default-used – ghik Nov 21 '13 at 23:32