11隐式转换
本文最后更新于 2021-08-05 11:42:59
隐式转换
隐式转换函数
object Implicit {
def main(args: Array[String]): Unit = {
implicit def double2Int(d:Double)=d.toInt
implicit def file2RichFile(file:File)=new RIchFile(file)
implicit def int2RichDate(day:Int)=new RichDate(day)
//正常情况下 会报错
//但是如果能找到implicit函数(在作用域),不看函数名只看参数和返回值 就会隐式调用
//如果找到多个符合条件的,就会报错
//把类自动转成自定义的类
val a:Int =10.1
//主要引用是给已有的类增加新的功能
val content = new File("/").richRead
println(content)
var ago = "ago"
var later ="later"
println(2.days(ago))
println(2 days ago) //!!!!!!!!!!!!
}
}
class RIchFile(file:File){
def richRead:String={
Source.fromFile(file,"utf-8").mkString
}
}
class RichDate(day:Int){
def days(when:String)={
if("ago"==when) LocalDate.now().minusDays(day).toString
else LocalDate.now().plusDays(day).toString
}
}隐式类
object Implicit2 {
def main(args: Array[String]): Unit = {
2 days "ago"
}
//隐式类
//隐式转换函数 优先级高于 隐式类
//只能作为内部类,不能做顶级的类
// 简化隐式函数操作
//保证隐式类的主构造参数为被转类型
//可以当作普通类使用
implicit class RichDate(day:Int){
def days(when:String)={
if("ago"==when) LocalDate.now().minusDays(day).toString
else LocalDate.now().plusDays(day).toString
}
}
}隐式值&隐式参数
object Implicit3 {
implicit val aa = 10
def main(args: Array[String]): Unit = {
//隐式参数通常与隐式值配和使用
//当调用的时候,如果不传递参数并且不加括号,就会自己找隐式值
//只看类型,不看具体的名字
fun
fun(10)
//如果有多个参数列表
//要么全部是隐式参数,要么都不用
//所以参数柯里化就有必要
fun2(1, 2)
fun3(1)
//优先使用隐式值,找不到使用默认值
fun4
//使用默认值
fun4()
}
//a就是隐式参数
def fun(implicit a: Int) = {
println(a)
}
def fun2(implicit a: Int, b: Double) = {
println(a + b)
}
def fun3(b: Double)(implicit a: Int) = {
println(a + b)
}
def fun4(implicit a:Int=10): Unit ={
}
}返回隐式值
object Implicit4 {
implicit val a:Int=10
def main(args: Array[String]): Unit = {
//def implicitly[T](implicit e: T) = e
val b:Int=implicitly[Int]
println(b)
}
}隐式值查找
- 先在当前作用域
- 如果找不到就去相关类型伴生对象(包含泛型)里面找
- 包对象也会找
- B2A 相关类型包括B、A
11隐式转换
https://jiajun.xyz/2020/11/11/scala/11隐式转换/