scala implicit 关键字、隐式转换、隐式变量、参数默认值
scala implicit 提供隐式转换和隐式变量两种功能
隐式转换,scala 对象由一种类型,隐式地转换成另外一种类型,如下:
package com.st.base object Main { def main(args: Array[String]): Unit = {
class Human{def speek(){println("human can speek")};};
// 下面两种方式,都可以让 Human 对象隐式转为 Monkey 对象 implicit class Monkey(human: Human){def sound(){println("monkey can't speek!")}}; implicit def converseToMonkey(human: Human): Monkey = { return new Monkey; } var human = new Human; human.speek(); human.sound(); // Human 对象被隐式转换为 Monkey 对象 } } 输出: human can speek monkey can't speek!
隐式变量,包括普通变量和参变量
package com.st.base object Main {
def main(args: Array[String]): Unit = {
// 定义隐式变量
implicit val name: String = "lili";
// name 隐式参数,way 默认值 bus,num 默认值 3
def goToSchool(implicit name: String, way: String = "bus", num: Int = 3): Unit ={
println(name + " go to school by " + way + " " + String.valueOf(num));
}
// name="lili",way= "lili", num = 3,隐式参数覆盖默认值
goToSchool;
// name = "xiaoming", way = "bus", num = 3, 实参覆盖隐式参数和默认值
goToSchool("xiaoming", "bike")
}
}
输出:
lili go to school by lili 3
xiaoming go to school by bike 3