10.3 隐式值

隐式值也叫隐式变量(也包括隐式形参).

将某个形参变量标记为implicit,所以编译器会在方法省略隐式参数的情况下去搜索作用域内的隐式值作为缺省参数

package com.atguigu.day10

object ImplicitDemo2 {
  // 隐式变量
  implicit var name: String = "jack"

  def main(args: Array[String]): Unit = {
    hello("hehe")
    // 当没有传递参数的时候, 会找类型为 String 的隐式变量
    hello
  }
  // 隐式参数
  def hello(implicit name: String): Unit = {
    val str: String = name + "你好..."
    println(str)
  }
}

总结:

  1. 调用函数的时候, 如果想使用隐式值就不能使用圆括号

  2. 当匹配到多个隐式值就会报错(匹配时,是按照类型匹配)(演示)

Copyright © 尚硅谷大数据 2019 all right reserved,powered by Gitbook
该文件最后修订时间: 2019-07-02 08:12:45

results matching ""

    No results matching ""