隐式2025.12.31

85 阅读1分钟
package imp

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

语法要求(必遵守,否则失效):

  1. 方法必须用 implicit 关键字修饰(核心标识);
  2. 方法有且仅有一个参数(待转换的源类型数据);
  3. 方法返回值为目标类型(要转换成的类型);
  4. 方法名自定义(推荐「源类型 2 目标类型」格式,见名知意,如 double2Int)。