Unikanie ukrytej dwuznaczności w Scali
Próbuję utworzyć niejawną konwersję z dowolnego typu (powiedzmy Int) na ciąg ...
Niejawna konwersja na łańcuch oznacza, że metody RichString (takie jak odwrotne) nie są dostępne.
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
Niejawna konwersja do RichString oznacza, że metody String (jak toCharArray) nie są dostępne
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
Korzystanie z obu niejawnych konwersji oznacza, że powielone metody (takie jak długość) są niejednoznaczne.
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: ?}
Czy więc możliwe jest niejawne przekonwertowanie na String i nadal obsługuje wszystkie metody String i RichString?