scala 使用 implicit 隐式转化时 , scala 编辑器发现对象的类型不匹配时,不会直接报错,而会在代码中尝试匹配implicit声明的object,
当然,相同方法签名的类必须唯一。
-------------------------------------------------------------------------------------------------------------------------------------------
定义隐式,给字符串添加上getApple方法,返回Apple类:
object AppleUtils {
implicit class get(s: String){
def getApple = new Apple(s)
}
}
case class Apple(name: String)
-------------------------------------------------------------------------------------------------------------------------------------------
调用,注意这里import进了AppleUtils._,导入所需的隐式方法。
import AppleUtils._
object GetFruit {
def main(args: Array[String]) {
val apple:Apple = "hello".getApple
println(apple.name)
}
}
输出:hello-------------------------------------------------------------------------------------------------------------------------------------------
一切看来都很美好,似乎可以抽根烟休息下,不过问题很快来了~~~
添加一个新的隐式方法,和AppleUtils一模一样:
object PearUtils {
implicit class get(s: String){
def getPear = new Pear(s)
}
}
case class Pear(name: String)
-------------------------------------------------------------------------------------------------------------------------------------------然后在测试的类里添加几行代码,改成:
import AppleUtils._
import PearUtils._
object GetFruit {
def main(args: Array[String]) {
val apple:Apple = "hello".getApple
println(apple.name)
val pear:Pear = "world".getPear
println(pear.name)
}
}
出错!!!!!!问题如下:
Error:(6, 31) value getApple is not a member of String
val apple:Apple = "hello".getApple
^
Error:(9, 29) value getPear is not a member of String
val pear:Pear = "world".getPear
^
-------------------------------------------------------------------------------------------------------------------------------------------
难道是implicit的作用域有问题?调试后,改为:
import AppleUtils._
object GetFruit {
def main(args: Array[String]) {
val apple:Apple = "hello".getApple
println(apple.name)
//将引入的方法,调整到这里!!
import PearUtils._
val pear:Pear = "world".getPear
println(pear.name)
}
}
正常运行,输出:
hello
world
-------------------------------------------------------------------------------------------------------------------------------------------
tips:出错原因暂时未知。进一步学习。
附上一片blog,有空细看:http://my.oschina.net/aiguozhe/blog/35968?catalog=115675