j'écris la conversion implicite suivante dans scala:Pourquoi ce type de conversion implicite est-il illégal?
implicit def strToInt2(str: String):Int = {
str.toInt
}
Mais il monte cette erreur de compilation:
<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
^
Si je supprime le type de retour, déclare simplement comme ceci:
implicit def strToInt2(str: String) = {
str.toInt
}
Il compile avec succès. Quelqu'un peut-il me dire quelle est la différence entre les deux?
Je ne connais pas la réponse exacte, mais je suppose qu'il y a une chaîne de conversion implicite -> int dans Predef. Donc, ajouter une nouvelle conversion de ce type rend les choses ambiguës. – dmitry