什么是隐式转换
我们经常引入第三方库,但当我们想要扩展新功能的时候通常是很不方便的,因为我们不能直接修改其代码。scala提供了隐式转换机制和隐式参数帮我们解决诸如这样的问题。
Scala中的隐式转换是一种非常强大的代码查找机制。当函数、构造器调用缺少参数或者某一实例调用了其他类型的方法导致编译不通过时,编译器会尝试搜索一些特定的区域,尝试使编译通过。
使用方式:
1.将方法或变量标记为implicit
class Man(val name: String)
object Man {
implicit def man2Superman(man: Man) = new SuperMan(man.name)
}
class SuperMan(val name: String) {
def makeMiracles = println(this.name + " is Strong!")
}
val man = new Man("Scala")
man.makeMiracles
2.将方法的参数列表标记为implicit
def talk(name:String)(implicit content:String) = println(name + " : " + content)
implicit val content = "is very funny"
talk("Scala")
talk("Scala")("is very very funny")
3.将类标记为implicit
class AntMan(val name: String)
class SuperMan(val name: String) {
def makeMiracles = println(this.name + " is Strong!")
}
object implicts {
implicit def antMan2Superman(antMan: AntMan) = new SuperMan(antMan.name)
}
val antMan = new AntMan("Spark")
import com.yrz.spark.scala.base.implicts._
antMan.makeMiracles
Scala支持两种形式的隐式转换:
隐式值:用于给方法提供参数
隐式视图:用于类型间转换或使针对某类型的方法能调用成功
完整例子如下:
class Man(val name: String)
object Man {
implicit def man2Superman(man: Man) = new SuperMan(man.name)
}
class AntMan(val name: String)
class SuperMan(val name: String) {
def makeMiracles = println(this.name + " is Strong!")
}
object implicts {
implicit def antMan2Superman(antMan: AntMan) = new SuperMan(antMan.name)
}
object HelloImplicit {
def main(args: Array[String]): Unit = {
val man = new Man("Scala")
man.makeMiracles
val antMan = new AntMan("Spark")
import com.yrz.spark.scala.base.implicts._
antMan.makeMiracles
implicit val content = "is very funny"
talk("Scala")
talk("Scala")("is very very funny")
}
def talk(name:String)(implicit content:String) = println(name + " : " + content)
}