目录
隐式转换概述
隐式转换实战
隐式参数
隐式类
隐式转换概述
什么是隐式转换
需求:为一个已存在的类添加一个新的方法
Java:动态代理
scala:隐式转换
双刃剑
spark/Hive/MapReduce 调优
隐式转换实战
package com.imooc.scala.course08
import java.io.File
import ImplicitAspect._
object ImplicitApp extends App {
//定义隐式转换函数即可
// implicit def man2superman(man: Man): Superman = new Superman(man.name)
val man = new Man("PK")
man.fly()
// implicit def file2RichFile(file: File): RichFile = new RichFile(file)
val file = new File("D:\\scala_test\\src\\com\\imooc\\scala\\course07\\hello.txt")
val txt = file.read()
println(txt)
}
class Man(val name: String) {
def eat(): Unit = {
println(s"man[ $name ] eat ...")
}
}
class Superman(val name: String) {
def fly(): Unit = {
println(s"superman[ $name ] fly ...")
}
}
class RichFile(val file: File) {
def read() = {
scala.io.Source.fromFile(file.getPath).mkString
}
}
另外一个文件
package com.imooc.scala.course08
import java.io.File
object ImplicitAspect extends App {
implicit def file2RichFile(file: File): RichFile = new RichFile(file)
implicit def man2superman(man: Man): Superman = new Superman(man.name)
}
隐式参数
指的是在函数或者方法中,定义一个用implicit修饰的参数,此时scala会尝试找到一个指定类型,用implicit修饰的对象,即隐式值,并注入参数
package com.imooc.scala.course08
object ImplicitApp extends App {
def testParam(implicit name: String): Unit = {
println(name + "---------")
}
// testParam("zhangsan")//zhangsan---------
// 可以在作用域找到
// implicit val name="implicit_name"
// testParam//implicit_name---------
// 报错
// implicit val s1 = "s1"
// implicit val s2 = "s2"
// testParam
}
隐式类
就是对类增加implicit限定的类,其作用主要是对类的加强
package com.imooc.scala.course08
object ImplicitClassApp extends App {
implicit class Calculator(x: Int) {
def add(a: Int) = a + x
}
println(1.add(3))
// 报错 因为定义的是Int类型
// println("1".add(3))
}