piszę następujące niejawna konwersja w Scala:Dlaczego ten typ niejawnej konwersji jest nielegalny?
implicit def strToInt2(str: String):Int = {
str.toInt
}
Ale wznosi ten błąd kompilacji:
<console>:9: error: type mismatch;
found : str.type (with underlying type String)
required: ?{val toInt: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method augmentString in object Predef of type (x: String)scala.collection.
immutable.StringOps
and method toi in object $iw of type (str: String)Int
are possible conversion functions from str.type to ?{val toInt: ?}
str.toInt
^
Jeśli usunąć typ zwracany, po prostu zadeklarować tak:
implicit def strToInt2(str: String) = {
str.toInt
}
Kompiluje się pomyślnie. Czy ktoś może mi powiedzieć, jaka jest różnica między tymi dwoma?
Nie znam dokładnej odpowiedzi, ale przypuszczam, że istnieje jeden niejawny ciąg konwersji -> int w Predef. Dodanie nowej konwersji tego typu powoduje, że są one niejednoznaczne. – dmitry