scala的隐式转换基本使用

24 阅读1分钟

1.什么是隐式转换

  • 隐式转换是指:scala自动把一种类型转成另一种类型的过程。这个过程对用户编程而言不可见,不需要用户手动编写代码。
object imp01 {
//隐式  偷偷的.....
  implicit def double2Int(d: Double): Int = {
    println("double2Int被调用了......")
    d.toInt
  }

  def main(args: Array[String]): Unit = {
    // 不能把Double类型 保存到Int。这样会有精度损失,不会自动做转换
    var i:Int = 1.1

    //可以把int类型保存到Double,会自动转换
    var d:Double = 1
  }
}

2.隐式函数

object imp01 {
//隐式  偷偷的.....
  //作用是:在类型转换的过程中,被自动调用
  //特点
//  1.自动调用
//  2.名字不重要,形参和返回值的类型是重要的!
  implicit def double2Int(d: Double): Int = {
    println("double2Int被调用了......")
    d.toInt
  }
  implicit def string2Int(d: String): Int = {
    println("string2Int被调用了......")
    1
  }

  def main(args: Array[String]): Unit = {
    // 不能把Double类型 保存到Int。这样会有精度损失,不会自动做转换
    var i:Int = 1.1

    i = 2.1
    i = 3.1


    i = "100"
    //可以把int类型保存到Double,会自动转换
    var d:Double = 1
  }
}

3.隐式参数

object imp02 {
  class KM(var value: Double) {
    override def toString(): String = s"${value}千米"
  }

  class M(var value: Double) {
    override def toString(): String = s"${value}米"
  }

  implicit def kmToM(km: KM): M = {
    new M(km.value * 1000)
  }


  def main(args: Array[String]): Unit = {
    val km1 = new KM(1)

    val m1:M = km1

    println(km1)
    println(m1)

  }
}

4.隐式转换

object imp03 {
  //1美元 = 6.9人民币
  //1人民币 = 0.14美元
  class MY(var value: Double) {
    override def toString(): String = s"${value}美元"
  }

  class RMB(var value: Double) {
    override def toString(): String = s"${value}人民币"
  }

  implicit def my2rmb(m: MY): RMB = {
    new RMB(m.value * 6.9)
  }

  implicit def rmb2my(r: RMB): MY = {
    new MY(r.value * 0.14)
  }


  def main(args: Array[String]): Unit = {
   val m1:RMB = new MY(100)
    println(m1)

    val my1:MY = new RMB(1000)
    println(my1)

  }
}