Scala学习笔记09--隐式转化implicit

 scala 使用 implicit 隐式转化时 ,  scala 编辑器发现对象的类型不匹配时,不会直接报错,而会在代码中尝试匹配implicit声明的object, 

当然,相同方法签名的类必须唯一。

-------------------------------------------------------------------------------------------------------------------------------------------

定义隐式,给字符串添加上getApple方法,返回Apple类:

  1. object AppleUtils {  
  2.   implicit class get(s: String){  
  3.     def getApple = new Apple(s)  
  4.   }  
  5. }  
  6.   
  7. case class Apple(name: String)  
-------------------------------------------------------------------------------------------------------------------------------------------


调用,注意这里import进了AppleUtils._,导入所需的隐式方法。

  1. import AppleUtils._  
  2.   
  3. object GetFruit {  
  4.   def main(args: Array[String]) {  
  5.     val apple:Apple = "hello".getApple  
  6.     println(apple.name)  
  7.   }  
  8. }  
输出:hello
-------------------------------------------------------------------------------------------------------------------------------------------

一切看来都很美好,似乎可以抽根烟休息下,不过问题很快来了~~~

添加一个新的隐式方法,和AppleUtils一模一样:

  1. object PearUtils {  
  2.   implicit class get(s: String){  
  3.     def getPear = new Pear(s)  
  4.   }  
  5. }  
  6.   
  7. case class Pear(name: String)  
-------------------------------------------------------------------------------------------------------------------------------------------
然后在测试的类里添加几行代码,改成:

  1. import AppleUtils._  
  2. import PearUtils._  
  3.   
  4. object GetFruit {  
  5.   def main(args: Array[String]) {  
  6.     val apple:Apple = "hello".getApple  
  7.     println(apple.name)  
  8.   
  9.     val pear:Pear = "world".getPear  
  10.     println(pear.name)  
  11.   }  
  12. }  

出错!!!!!!问题如下:

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的作用域有问题?调试后,改为:

  1. import AppleUtils._  
  2.   
  3. object GetFruit {  
  4.   def main(args: Array[String]) {  
  5.     val apple:Apple = "hello".getApple  
  6.     println(apple.name)  
  7.   
  8.     //将引入的方法,调整到这里!!  
  9.     import PearUtils._  
  10.     val pear:Pear = "world".getPear  
  11.     println(pear.name)  
  12.   }  
  13. }  
正常运行,输出:

hello

world

-------------------------------------------------------------------------------------------------------------------------------------------

tips:出错原因暂时未知。进一步学习。

附上一片blog,有空细看:http://my.oschina.net/aiguozhe/blog/35968?catalog=115675



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值