1.什么是隐式转换
- 隐式转换是指:scala自动把一种类型转成另一种类型的过程。这个过程对用户编程而言不可见,不需要用户手动编写代码。
object imp01 {
implicit def double2Int(d: Double): Int = {
println("double2Int被调用了......")
d.toInt
}
def main(args: Array[String]): Unit = {
var i:Int = 1.1
var d:Double = 1
}
}
2.隐式函数
object imp01 {
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 = {
var i:Int = 1.1
i = 2.1
i = 3.1
i = "100"
var d:Double = 1
}
}
3.隐式参数
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 kmToM(km: KM): M = {
new M(km.value * 1000)
}
def main(args: Array[String]): Unit = {
val km1 = new KM(1)
val m1:M = km1
println(km1)
println(m1)
}
}
4.隐式转换
object imp03 {
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(m: MY): RMB = {
new RMB(m.value * 6.9)
}
implicit def rmb2my(r: RMB): MY = {
new MY(r.value * 0.14)
}
def main(args: Array[String]): Unit = {
val m1:RMB = new MY(100)
println(m1)
val my1:MY = new RMB(1000)
println(my1)
}
}