scala隐式转换
1、隐式转换概念
2、隐式转换实战
package com.imooc.scala.scala8
import java.io.File
/**
- 隐式转换
*/
object ImplicitApp extends App {
//案例一
//定义隐式转换,可以让普通人的类Man,拥有超人类Superman的能力飞
//implicit:隐式转换的定义
//def :方法,man2superman:方法名
//要转换的类:(man:Man)
//要转换成的类:Superman = new Superman(man.name),man.name传的是一个名字
implicit def man2superman(man:Man):Superman = new Superman(man.name)
val man = new Man(“zhapxiaoba”)
man.fly()
//案例二
//把file方法直接增加读的功能
implicit def file2RichFile(file: File):RichFile = new RichFile(file)
val file = new File("/Users/zhaoxinbo/Documents/python-xiangmu/data/scala_work.txt")
val txt = file.read()
println(txt)
}
/**
- 定义一个普通人的类,方法吃饭
*/
class Man(val name:String){
//普通人吃饭
def eat(): Unit ={
println(s"普通人[$name]只会吃饭…")
}
}
/**
- 定义一个超人的类,方法飞
*/
class Superman(val name:String){
//超人会飞
def fly(): Unit ={
println(s"超人[$name]是会飞的…")
}
}
class RichFile(val file:File){
def read()={
scala.io.Source.fromFile(file.getPath).getLines().toList.mkString
}
}
3、隐式转换切面封装
package com.imooc.scala.scala8
import java.io.File
/**
- 隐式转换封装
*/
object ImplicitAspect {
//定义隐式转换,可以让普通人的类Man,拥有超人类Superman的能力飞
implicit def man2superman(man:Man):Superman = new Superman(man.name)
//把file方法直接增加读的功能
implicit def file2RichFile(file: File):RichFile = new RichFile(file)
}
package com.imooc.scala.scala8
import java.io.File
import ImplicitAspect._ //导入隐式转换封装包
/**
- 隐式转换
*/
object ImplicitApp extends App {
//案例一
//定义隐式转换,可以让普通人的类Man,拥有超人类Superman的能力飞
//implicit:隐式转换的定义
//def :方法,man2superman:方法名
//要转换的类:(man:Man)
//要转换成的类:Superman = new Superman(man.name),man.name传的是一个名字
val man = new Man(“zhapxiaoba”)
man.fly()
//案例二
//把file方法直接增加读的功能
val file = new File("/Users/zhaoxinbo/Documents/python-xiangmu/data/scala_work.txt")
val txt = file.read()
println(txt)
}
/**
- 定义一个普通人的类,方法吃饭
*/
class Man(val name:String){
//普通人吃饭
def eat(): Unit ={
println(s"普通人[$name]只会吃饭…")
}
}
/**
- 定义一个超人的类,方法飞
*/
class Superman(val name:String){
//超人会飞
def fly(): Unit ={
println(s"超人[$name]是会飞的…")
}
}
class RichFile(val file:File){
def read()={
scala.io.Source.fromFile(file.getPath).getLines().toList.mkString
}
}
4、隐式参数
5、隐式类