1, T: M Context Definition
View Definition T <% V requires that there be an implicit conversion from T to V in. Defined in the context of the form T: M, where M is another generic class, it implicitly requires the existence of a value of type M [T] is.
The following class definition requires the existence of a type of implicit value Ordering [T] when you use a method using an implicit value, passing the implicit parameter.
class Pair6[T: Ordering](val first: T, val second: T) {
def smaller(implicit ord: Ordering[T]) = {
println(ord)
if (ord.compare(first, second) < 0) first else second
}
override def toString = "(" + first + "," + second + ")"
}
object Main6 extends App{
override def main(args: Array[String]): Unit = {
val p6 = new Pair6(1, 2)
println(p6.smaller)
}
}
2, simple to understand hermit conversion
object Logger {
def main(args: Array[String]): Unit = {
implicit val x:Int = 10
def play1(implicit x:Int): Unit ={
println(x)
}
play1
}
}
尖叫提示:调用play1,没有传参数,x进去了,打印10,这句话的意思是,定义了一个play1函数,传一个参数,这个参数是隐士的,可以传,也可以不传,如果你不传的话,它会在play1当前方法所在的作用域里面,去找 有没有和play1参数一样的隐士变量,有的话就可以,当然隐士转换不能出现二义性
Reproduced in: https: //www.jianshu.com/p/63c3e0b6d54c