scala的隐式转换基本使用

10 阅读1分钟
package imp

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
  }
}

image.png

package imp

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 km2m(km:KM):M={
      new M(1000 * km.value)
  }

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

image.png

package imp

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(my:MY):RMB={
    new RMB(my.value * 6.9)
  }
  implicit def rmb2my(my:MY):MY={
    new MY (my.value * 0.14)
  }
  def main(args: Array[String]): Unit = {
    val m1: RMB = new MY(100)
    println(m1)
    val my1:RMB = new RMB(1000)
    println(my1)
  }
}

image.png