
上QQ阅读APP看书,第一时间看更新
Implicit parameters
An implicit parameter is an actual parameter, which is a value passed to a function (or method) in a function (or method) call. When a method (or function) has an implicit parameter, it's up to the developer to pass it explicitly, or make it available in the current scope to pass it automatically to the Scala compiler.
Consider the following example:
scala> def add(x: Int, implicit y: Int) = x + y <console>:1: error: identifier expected but 'implicit' found. def add(x: Int, implicit y: Int) = x + y ^ scala> def add(x: Int) (implicit y: Int) = x + y add: (x: Int)(implicit y: Int)Int scala> add(11) <console>:15: error: could not find implicit value for parameter y: Int add(11) ^ scala> implicit a:Int = 12 <console>:1: error: expected start of definition implicit a:Int = 12 ^ scala> implicit val a:Int = 12 a: Int = 12 scala> add(11) res1: Int = 23