Scala - 如何不调用一元方法
Scala - how to not call a unary method
我有这个代码:
def +(s: String) = s.headOption
val foo = +("hello")
尝试编译时,出现编译错误:
Error: value unary_+ is not a member of String
val foo = +("hello")
如何防止编译器插入对 String.unary_-
的调用,而是在范围内调用该方法?
val foo = this.+("hello") //this will call the class, object etc. and you will get the correct reference for the method :)
或者:
import <path>._
val foo = classname.+("hello")
或者:
import <path>.<class>
val foo = <class>.+("hello")
例如:
package test
object SO {
def +(s:String) = s.headOption
}
package test
object add extends App {
import test.SO
println(SO.+("hello"))
}
回复:
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"))
}
回复:
Some(s)
我有这个代码:
def +(s: String) = s.headOption
val foo = +("hello")
尝试编译时,出现编译错误:
Error: value unary_+ is not a member of String
val foo = +("hello")
如何防止编译器插入对 String.unary_-
的调用,而是在范围内调用该方法?
val foo = this.+("hello") //this will call the class, object etc. and you will get the correct reference for the method :)
或者:
import <path>._
val foo = classname.+("hello")
或者:
import <path>.<class>
val foo = <class>.+("hello")
例如:
package test
object SO {
def +(s:String) = s.headOption
}
package test
object add extends App {
import test.SO
println(SO.+("hello"))
}
回复:
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"))
}
回复:
Some(s)