2016-10-05 2 views
1

J'ai ce code:Scala - comment ne pas appeler une méthode unaire

def +(s: String) = s.headOption 

val foo = +("hello") 

Lorsque vous essayez de le compiler, je reçois une erreur de compilation:

Error: value unary_+ is not a member of String 
    val foo = +("hello") 

Comment puis-je empêcher le compilateur de insérer un appel à String.unary_-, mais appeler plutôt la méthode dans la portée?

+0

Il y a un problème pour pourquoi est-il nécessaire de 'this.f (arg)' pour obtenir la conversion implicite 'this' (conversion à quelque chose avec 'f'), pourquoi n'est-ce pas' f (arg) 'assez. Cela pourrait être un bon exemple pourquoi pas. Ou, peut-être qu'ils sont tous les deux un argument pour essayer 'this.expr' avant d'échouer. –

Répondre

1
val foo = this.+("hello") //this will call the class, object etc. and you will get the correct reference for the method :) 

Ou:

import <path>._ 

val foo = classname.+("hello") 

Ou:

import <path>.<class> 

val foo = <class>.+("hello") 

Ex:

package test 

object SO { 

    def +(s:String) = s.headOption 

} 

package test 

object add extends App { 
    import test.SO 

    println(SO.+("hello")) 
} 

Res:

Some(h) 

Ex2:

package test 

class SO {} 
object SO { 
    def apply(): SO = { 
     new SO 
    } 
    def +(s:String) = s.headOption 
} 



package test 

object add extends App { 
    import test.SO 

    println(SO.+("string")) 
} 

Res:

Some(s) 
+0

l'avez-vous essayé? – Dima

+0

Cela ne fonctionne pas si la méthode est importée –

+0

@Dima oui et cela fonctionne – Jonatan