I have this code:
def +(s: String) = s.headOption
val foo = +("hello")
When trying to compile it , I get a compiler error:
Error: value unary_+ is not a member of String
val foo = +("hello")
How can I prevent the compiler from inserting a call to String.unary_-
, but instead call the method in scope?
val foo = this.+("hello") //this will call the class, object etc. and you will get the correct reference for the method :)
Or:
import <path>._
val foo = classname.+("hello")
Or:
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)