scala 隐式转换

36 阅读1分钟
package imp

object imp01 {
  //隐式转换函数
  //1.用关键字implicit 修饰
  //2.它的函数名不重复() 重置的是它的 参数和返回值的类型
  //!!!:不能写两个同类型的 (参数和返回值的类型都一样) 的隐式转换函数 会报错

  //它的参数是Double 它的返回值是Int 它的作用是: 当代码中出现了需要将Double转换成Int的时候 系统会自动调用它
  implicit def DoubleToInt(x:Double):Int = {
    println("double to int...")
    x.toInt
  }
//  implicit def DoubleToInt(x:Double):Int = {
//    println("double to int...")
//    x.toInt
//  }

  def main(args: Array[String]): Unit = {
    //1.隐式转换
    var i:Int = 1;

    var d:Double = 1.1;

    d = i//将int -> double类型
    //d = i.toDouble
    //println(s"d=${d}")
    i = d //存在一个隐式转换 将double -> int 报错
    i = 100.1
    i = 100.1
  }
}