Knowledge point: Implicit variables
important point:
- No declaration, can not be used directly
- A method that cannot find multiple implicit variables at the same time, otherwise an error will be reported
- If a value is explicitly specified, the implicit value has no effect
Test code:
package demo.scala object TestImplicit1 { def test(implicit name: String) = { println("name=" + name) } def main(args: Array[String]): Unit = { //1. Direct call, no implicit parameters, result: name=abc test("abc") //2.报错:could not find implicit value for parameter name: String //test //3. Implicit parameters are found and used directly, so test will not report an error, the result: name=implicit_name implicit val abc = "implicit_name" test //4. When the display is specified, the value of the implicit parameter will not be used, the result: name=abc test("abc") //5. Define another implicit variable of type string, and an error will be reported, because the method test finds two implicit variables of type string: ambiguous implicit values: both value s1 of type String and value abc of type String match expected type String test // implicit val s1 = "s1" } }