概念

  1. 隐式转换可以在不需改任何代码的情况下,扩展某个类的功能。<br />使用场景:<br /> 可以给已有的类增加功能.

案例


通过隐式转化为Int类型增加方法

class MyRichInt(val self: Int) {
    def myMax(i: Int): Int = {
        if (self < i) i else self
    }

    def myMin(i: Int): Int = {
        if (self < i) self else i
    }
}

object TestImplicitFunction {
    // 使用implicit关键字声明的函数称之为隐式函数
    implicit def convert(arg: Int): MyRichInt = {
        new MyRichInt(arg)
    }

def main(args: Array[String]): Unit = {
    // 当想调用对象功能时,如果编译错误,那么编译器会尝试在当前作用域范围内查找能调用对应功能的转换规则,这个调用过程是由编译器完成的,所以称之为隐式转换。也称之为自动转换
        println(2.myMax(6))
    }
}

double转换int函数

隐式函数需要有一个参数加一个返回值,    在需要转换的地方不看函数名, 只看参数和返回值类型,需要注意的是只能有一个满足的隐式转换函数,如果有两个满足的隐式转换函数的话编译器会报错,但是其实你也可以思考一下,正常些代码的时候你也不可能写两个转换功能一样的隐式转换函数,比如说把double转成int的方式用一个就行了,不可能一个页面用两种double转成int的方式.
object Implicit1 {
  //implicit关键字
  implicit def double2Int(d: Double) = d.toInt
  def main(args: Array[String]): Unit = {


    val a: Int = 10.1
    val b: Int = 20.2
    println(a)
    println(b)
  }
}

将Java的File类转换成自己写的类


import java.io.File
import scala.io.Source


object Implicit2 {
  def main(args: Array[String]): Unit = {
    implicit def file2RichFile(file: File): RichFile = new RichFile(file)

    val content: String = new File("E:\\ZJJ_Neaten5.10\\ZJJ_Scala\\demo\\src\\main\\java\\implicitdemo\\Implicit2.scala")
      .readContent
    println(content)
  }
}

class RichFile(file: File) {
  def readContent: String = {
    Source.fromFile(file, "utf-8").mkString
  }
}

输出: 就是输出 Implicit2.scala 文件里面的文本,这里就不粘贴到这里了.

案例扩展现有的类

案例1:
输入一段英文的句子就能算出来一些东西.
输出2 days ago 就计算前两天是哪一天

import java.time.LocalDate
object Implicit3 {
  def main(args: Array[String]): Unit = {
    implicit def int2RichDate(day: Int) = new RichDate(day)
    // 计算2天前是哪一天
    val ago = "ago"
    val r = 2 days ago
    println(r) // 2020-11-04
  }
}
class RichDate(day: Int) {
  def days(when: String) = {
    if ("ago" == when)
      LocalDate.now().plusDays(-day).toString
    else {
      LocalDate.now().plusDays(day).toString
    }
  }
}

输出:

2020-11-04


输出 5 days later 计算的是五天后的值:
**

import java.time.LocalDate
object Implicit3 {
  def main(args: Array[String]): Unit = {
    implicit def int2RichDate(day: Int) = new RichDate(day)
    val later = "later"
    // 5天后的值
    val r  = 5 days later
//    val r = 5.days(later)
    println(r) // 2020-11-04
  }
}
class RichDate(day: Int) {
  def days(when: String) = {
    if ("ago" == when)
      LocalDate.now().plusDays(-day).toString
    //            LocalDate.now().minusDays(day)
    else {
      LocalDate.now().plusDays(day).toString
    }
  }
}