1.隐式值
object ScalaDemo { implicit val str : String = "刘明" def main(args: Array[String]): Unit = { //匹配隐式值时,不加括号 show } def show(implicit name:String)={ print("name: " + name) } }
2.隐式方法
object ScalaDemo { def main(args: Array[String]): Unit = { val aa = new AA aa.methodAA() //创建了AA,经隐式方法转换,能调用BB里的方法 aa.methodBB() } implicit def AB(a:AA):BB={ new BB } } class AA { def methodAA(): Unit ={ println("methodAA...") } } class BB { def methodBB(): Unit ={ println("methodBB...") } }
3.隐式类
object ScalaDemo { def main(args: Array[String]): Unit = { val aa = new AA aa.methodAA() //创建了AA,经隐式类的主构造器转换,能调用BB里的所有方法 aa.methodBB() aa.methodBB2() } implicit class BB(aa: AA) { def methodBB(): Unit ={ println("methodBB...") } def methodBB2(): Unit ={ println("methodBB2...") } } } class AA { def methodAA(): Unit ={ println("methodAA...") } }
原文:https://www.cnblogs.com/noyouth/p/12703328.html