scala 随笔(4) implicit 隐式转换 和冲突解决

来源:互联网 发布:面向对象编程的优势 编辑:程序博客网 时间:2024/06/05 12:45
scala 的隐式转换类似于C#的扩展,也类似于extends,也就增加对象方法或者属性。

主要是对对象进行方法的扩展
例如:
  1. class Implicit(val x :Int){
  2. def f = x+1;
  3. }
  4. object Implicit {
  5. def main(args: Array[String]): Unit = {
  6. val myImplicit = new Implicit(2);
  7. println(myImplicit.f)
  8. // println(myImplicit.y) //目前编译是不同过的
  9. }
  10. }
如果需要对Implicit进行方法扩展,可以
class Implicit(val x :Int){  def f = x+1;}object Implicit {  implicit  class anyName(s:Implicit) {  //这里    def y = 10+s.x  }  def main(args: Array[String]): Unit = {    val myImplicit = new Implicit(2);    println(myImplicit.f)    println(myImplicit.y) //这里  }}
class 后面的anyName 代表这个类名不重要,重要的是implicit 这个关键字,以及输入的参数(S:Implicit

当然你可能想直接将def y=10,放在上面Implicit里面不就可以了。

如果你能这么想,说明你很聪明了,但是如果是String这个类呢。你不可能去改源代码吧,难道为了一个方法写一个类。


2) 省略方法
再看一个例子。
object Implicit {  implicit def translate(s:Double) ={    s.toInt  }  def main(args: Array[String]): Unit = {    val x:Int = 4.5  }}

将一个double 转换成了int型,背后是省去了translate这个方法。

这个implicit 也有冲突的时候,
如果冲突出现,必须指明是调用了哪个方法。

3)冲突解决
比如:
  1. object Implicit {
  2. implicit def translate(s:Int) ={
  3. s.toString.toList.mkString(":")
  4. }
  5. implicit def translate2(s:Int) ={
  6. s.toString.toList.mkString(":")
  7. }
  8. def main(args: Array[String]): Unit = {
  9. val x:Int =123;
  10. val y :String = x + 12
  11. println(y)
  12. }
  13. }
编译不通过
如果 没有translate2 ,将输出1:3:5
这个时候需要指明是调用哪个translate2

当与系统默认的方法冲突是,会首先调用默认方法,这里调用默认方法+ ,不会调用的translate
object Implicit {  implicit def translate(s:Int) ={    s.toString.toList.mkString(":")  }  def main(args: Array[String]): Unit = {    val x:Int =123;    val y :String  = x + "12"    println(y)  }}
输出:135

到此结束


有问题可以留言
原创粉丝点击