R – Avoiding implicit def ambiguity in Scala

ambiguousimplicitscalastring

I am trying to create an implicit conversion from any type (say, Int) to a String…

An implicit conversion to String means RichString methods (like reverse) are not available.

implicit def intToString(i: Int) = String.valueOf(i)
100.toCharArray  // => Array[Char] = Array(1, 0, 0)
100.reverse // => error: value reverse is not a member of Int
100.length // => 3

An implicit conversion to RichString means String methods (like toCharArray) are not available

implicit def intToRichString(i: Int) = new RichString(String.valueOf(i))
100.reverse // => "001"
100.toCharArray  // => error: value toCharArray is not a member of Int
100.length // => 3

Using both implicit conversions means duplicated methods (like length) are ambiguous.

implicit def intToString(i: Int) = String.valueOf(i)
implicit def intToRichString(i: Int) = new RichString(String.valueOf(i))
100.toCharArray  // => Array[Char] = Array(1, 0, 0)
100.reverse // => "001"
100.length // => both method intToString in object $iw of type 
   // (Int)java.lang.String and method intToRichString in object
   // $iw of type (Int)scala.runtime.RichString are possible 
   // conversion functions from Int to ?{val length: ?}

So, is it possible to implicitly convert to String and still support all String and RichString methods?

Best Answer

Either make a huge proxy class, or suck it up and require the client to disambiguate it:

100.asInstanceOf[String].length

Related Topic