L'exemple suivant provient du livre 'Programming in Scala'. Étant donné une classe « rationnelle » et la définition de méthode suivante:Scala: méthode surcharge de l'opérateur
def add(that: Rational): Rational =
new Rational(
this.numer * that.denom + that.numer * this.denom,
this.denom * that.denom
)
Je peux surcharger avec succès la méthode d'ajout d'une version pratique qui prend un argument Int et utilise la définition ci-dessus:
def add(that: Int): Rational =
add(new Rational(that, 1))
Aucun problème jusqu'à présent.
Maintenant, si je change le nom de la méthode à un nom de style de l'opérateur:
def +(that: Rational): Rational =
new Rational(
this.numer * that.denom + that.numer * this.denom,
this.denom * that.denom
)
Et surcharge comme ceci:
def +(that: Int): Rational =
+(new Rational(that, 1))
Je reçois l'erreur de compilation suivante:
(fragment of Rational.scala):19: error: value unary_+ is not a member of this.Rational
+(new Rational(that, 1))
^
Pourquoi le compilateur recherche-t-il une version unaire de la méthode +
?