/**
  * Created by root
  * Description : 隐式值和隐式视图
  */
object ImplicitTest {

  def main(args: Array[String]): Unit = {

    // 隐式值
    implicit val str = "hello"
    def fun(implicit s: String) = println(s)
    fun  // 调用fun函数,编译器发现参数缺省,直接去作用域内查找隐式值,保证隐式值只有一个

    // 隐式视图:隐式转换为目标类型:把一种类型自动转换到另一种类型
    implicit def intToString(a : Int) = a.toString
    implicit def intToByte(a : Int) = a.toByte
    def fun2(s: String) = println(s)
    fun2(100) //调用fun2函数,参数是个整数,编译器发现函数参数类型不一致,直接去作用域内查找符合编译通过的类型

  }

}

 

相关文章:

  • 2022-12-23
  • 2021-09-27
  • 2021-11-24
  • 2021-12-12
  • 2021-08-20
猜你喜欢
  • 2021-03-31
  • 2022-12-23
  • 2021-12-05
  • 2021-09-14
  • 2022-12-23
  • 2021-12-06
相关资源
相似解决方案