隐式转换条件:
1. 当表达式类型与预期的类型不同时
2.当对象访问一个不存在的成员时
3.当对象调用某个方法,而该方法的参数声明与传入参数不相匹时。
隐式转换搜索范围:
1. 位于源火目标类型伴生对象中的隐式函数。
2. 位于当前作用域可以以单个标识符指代的隐式函数。
隐式参数条件:
函数中参数带有implicit
隐式参数搜索范围:
在当前作用域所有可以用单个标识符指代的满足类型要求的val和def。
与所要求类型相关联的类型的伴生对象。
隐式参数和隐式转换并用例子:
class A { def say() = {
println("Hi Sky")
}
} object A {
implicit def A2B(a: A): B = {
new B()
}
} class B { } object B { } object ImplicitParamConvert { def sayHello(a: A)(implicit b: A => B) = {
a.say()
} def main(args: Array[String]): Unit = {
sayHello(new A())
}
}
输出结果:
Hi Sky