1.隱式參數
相當於默認參數
2.隱式轉換
如果參數、變量、屬性的類型不對,則會按隱式轉換方法轉換成正確的類型
3.隱式類
x沒有某一方法,則把x轉換成隱式類,而隱式類剛好有這個方法,則調用隱式類的方法
示例如下:
object ImplicitDemo {
// 隱式參數(默認參數)
implicit val parameter1: Int = 100
implicit val parameter2: String = "boy"
def a(implicit param: Int): Unit = {println(param)}
def b(param1: String)(implicit param2: String): Unit = {println("b:" + "param1:" + param1 + "param2:" + param2)}
// 隱式轉換(類型默認轉換)
def display(input:String):Unit = println(input)
def xx(i: String):Unit = {println(i)}
implicit def typeConvertor(input:Int):String = input.toString
implicit def typeConvertor(input:Boolean):String = if(input) "true" else "false"
implicit def typeConvertor(input:Double):String = input.toString
// implicit def booleanTypeConvertor(input:Boolean):String = if(input) "true" else "false"
// 隱式類(默認類)
implicit class I(p: Int) {
def good(): Unit = {println("p:" + p)}
}
def main(args: Array[String]): Unit = {
// 隱式參數(默認參數)
a
b("這是第一個參數")
b("這是第一個參數")("這是第二個參數")
// 隱式轉換(類型默認轉換)
val y: String = 9
println(y)
display("1212")
display(12)
display(true)
xx(1212)
xx(false)
xx(12.32)
// 隱式類(默認類)
val o: Int = 9
o.good()
}
}