Black monkey house: Scala implicit value

1, case a practical operation

The variable name is marked as Implicit, the compiler will be omitted in the case of a hidden parameter in the process continues, the value of the implicit search scope as missing parameter.

implicit val name = "Nick"
def person(implicit name: String) = name
println(person)

2, ambiguity

But this time it will error if you define the same scope but also an implicit variable, call the method again, ambiguity

implicit val name = "Nick"
implicit val name2 = "Nick"
def person(implicit name: String) = name
println(person)

3, two cases of practical operation

object RichFileMain{
  def main(args: Array[String]): Unit = {
    def foo(msg : String) = msg
    implicit def intToString(x : Int) = x.toString
    println(foo(10))
    println(foo(10).getClass.getTypeName)
  }
}

Implicit in the underworld live value, and in a manner invisible to the process is added

Reproduced in: https: //www.jianshu.com/p/3d9870ce1e3a

Guess you like

Origin blog.csdn.net/weixin_33725515/article/details/91182535