一、隐式转换需求
为一个已存在的类添加一个新的方法?
scala使用隐式转换方法:implicit
二、隐式转换示例一
object ImplicitApp extends App{
//定义隐式转换函数即可,Man调用Superman的fly方法
implicit def man2superman(man:Man):Superman = new Superman(man.name)
val man = new Man("张三")
man.fly()
}
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 .........")
}
}
三、隐式转换示例二
import java.io.File
object ImplicitApp extends App{
//定义隐式转换函数即可
implicit def file2RichFile(file:File):RichFile = new RichFile(file)
val f = new File("D:\\test\\test.txt")
val txt = f.read()
println(txt)
}
class RichFile(val file:File){
def read()={
scala.io.Source.fromFile(file.getPath).mkString
}
}
四、隐式转换切面封装
建一个切面类,将上面三和四中的定义的隐式函数提取出来,并将切面类导入到需要使用的类中 【 import ImplicitAspect._ 】
import java.io.File
object ImplicitAspect {
implicit def man2superman(man:Man):Superman = new Superman(man.name)
implicit def file2RichFile(file:File):RichFile = new RichFile(file)
}
import java.io.File
import ImplicitAspect._
object ImplicitApp extends App{
//定义隐式转换函数即可
// implicit def man2superman(man:Man):Superman = new Superman(man.name)
val man = new Man("张三")
man.fly()
//implicit def file2RichFile(file:File):RichFile = new RichFile(file)
val f = new File("D:\\test\\test.txt")
val txt = f.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
}
}