scala-隐式转换

//隐式转换示例

class Persion(val name: String) {

}

class Worker(name: String) extends Persion(name) {

}

class Dog(val name: String) {

}


def test1[T <% Persion](p: T): Unit = {
}

test1(new Dog("123"))

implicit def method1(obj: Object): Persion = {//只要定义了隐式转换函数,那么view bound([T <% Persion])泛型就可以接收指定类型
  if (obj.isInstanceOf[Dog]) {
    val d = obj.asInstanceOf[Dog];
    new Persion(d.name);
  } else Nil
}

 隐式转换发生的3种情况:

1:在调用函数时参数类型不匹配;

2:在对象调用不存在方法的时候;

3:在调用类型对象的方法但参数不匹配的时候;

隐式转换的搜索范围:

1:在当前的scala上下文范围内搜索;

2:在目标类或者原类的伴生对象中搜索;

//隐式参数应用

def test(name: Int)(implicit age: Int): Unit = {
  println(name + "  -  " + age)
}

implicit val age = 16

test(99)

 

posted @ 2018-03-22 20:52  soft.push("zzq")  Views(122)  Comments(0Edit  收藏  举报