补全代码:
object class14 {
implicit def double2Int(d:Double):Int = {
println("double2Int被调用了...")
d.toInt
}
def main(args: Array[String]): Unit = {
var i:Int = 1.1
i = 2.1
i = 3.1
i = "100"
var d:Double = 1
}
}
- 原代码中
double2Int只能处理Double转Int,但i = "100"是String转Int,会报错,需要新增String转Int的隐式转换方法。 var d:Double = 1是Int转Double,Scala 默认支持,但为了代码完整性,可显式定义(也可省略,不影响运行)。- 最终目标是让所有类型赋值语句通过隐式转换正常执行,并打印对应的转换日志。
补全后:
object class14 {
// Double转Int的隐式转换
implicit def double2Int(d: Double): Int = {
println("double2Int被调用了...")
d.toInt
}
// String转Int的隐式转换(解决i = "100"的类型问题)
implicit def string2Int(s: String): Int = {
println("string2Int被调用了...")
// 增加异常处理,避免字符串无法转数字的情况
try {
s.toInt
} catch {
case e: NumberFormatException =>
println(s"字符串${s}无法转换为整数,返回默认值0")
0
}
}
// Int转Double的隐式转换(可选,Scala默认支持,显式定义更清晰)
implicit def int2Double(i: Int): Double = {
println("int2Double被调用了...")
i.toDouble
}
def main(args: Array[String]): Unit = {
var i: Int = 1.1 // 触发double2Int
i = 2.1 // 触发double2Int
i = 3.1 // 触发double2Int
i = "100" // 触发string2Int
var d: Double = 1 // 触发int2Double(若省略该隐式转换,Scala默认处理)
// 打印最终值,验证转换结果
println(s"最终i的值:$i")
println(s"最终d的值:$d")
}
}
运行结果
double2Int被调用了...
double2Int被调用了...
double2Int被调用了...
string2Int被调用了...
int2Double被调用了...
最终i的值:100
最终d的值:1.0