scala隐式转换
1. 目的
增强功能
2. 增强类
package com.hpznyf.implicitSource
import java.io.File
import scala.io.Source
import implicitAspect._
object implicitApp {
def main(args: Array[String]): Unit = {
val man = new Man("张三")
man.fly()
val file = new File("data/input/ck")
println(file.read)
}
}
class Man(val name: String) // File
class superMan(val name: String){ //RichFile
def fly(): Unit ={
println(s"$name can fly")
}
}
class RichFile(val file:File){
def read = Source.fromFile(file.getPath).mkString
}
切面
package com.hpznyf.implicitSource
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)
}
3. 隐式类
package com.hpznyf.implicitSource
import java.io.File
import java.time.LocalDate
import scala.io.Source
object implicitClassApp {
def main(args: Array[String]): Unit = {
println(new File("data/input/ck").read)
println(1.add(2))
println(1.days("ago"))
println(2.days("later"))
}
//在隐式类中为file增强read方法
implicit class EnhenceFile(file:File){
def read = Source.fromFile(file.getPath).mkString
}
//隐式类转换 Int 1.add(2)
implicit class Calculator(x: Int){
def add(a:Int) = x + a
}
implicit class RichDate(day: Int){
def days(when: String) ={
if("ago" == when){
LocalDate.now().plusDays(-day).toString
}
else if("age" == when){
LocalDate.now().plusDays(day).toString
}
else{
LocalDate.now().toString
}
}
}
}
4. 隐式参数0
package com.hpznyf.implicitSource
object implicitParamsAPP {
def main(args: Array[String]): Unit = {
def add(a:Int)(implicit b:Int, c:Int) = a + b + c
//将x= 10 映射给参数 b c
implicit val x = 10
println(add(5))
}
}