(一)隐式转换
隐式转换是指:scala自动把一种类型转成另一种类型的过程
(二)隐式函数
隐式函数的定义:通过implicit关键字修饰的函数,它的功能是把一种类型的数据转成另一种类型。
(1)调用时机,在系统自动把数据从类型1隐式转为类型2时出错时,被自动调用。
(2)函数名可以自定义(一般取名为类型1to类型2),但是参数和返回值必须有限制。
package imp
object imp01 {
implicit def double2Int(d: Double): Int = {
println("double2Int被调用了......")
d.toInt
}
implicit def string2Int(s: String): Int = {
println("string2Int被调用了......")
1
}
def main(args: Array[String]): Unit = {
var i: Int = 1.1
i =2.1
i =3.1
i="100"
var d: Double = 1
}
}
千米和米之间的转换
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)
}
}
人民币和美元
package imp
object imp03 {
class MY(var value: Double) {
override def toString: String = s"${value}美元"
}
class RNB(var value: Double) {
override def toString: String = s"${value}人民币"
}
implicit def my2rnb(m: MY): RNB = {
new RNB(m.value * 6.9)
}
def main(args: Array[String]): Unit = {
val m1:RNB = new MY(100)
println(m1)
}
}