Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called. In simpler terms, if no value or parameter is passed to a method or function, then the compiler will look for implicit value and pass it further as the parameter. For example, changing an integer variable to a string variable can be done by a Scala compiler rather than calling it explicitly. When implicit keyword used in the parameter scope of the function, all the parameters are marked as implicit.
Note: A method can only contain one implicit keyword.
Syntax:
def func1(implicit x : Int) // x is implicit
def func2(implicit x : Int, y : Int) // x and y both are implicit
def func3 (x : Int)(implicit y : Int) // only y is implicit
Example 1:
object Main{
def main(args : Array[String])
{
val value = 10
implicit val multiplier = 3
def multiply( implicit by : Int) = value * by
// Implicit parameter will be passed here
val result = multiply
// It will print 30 as a result
println(result)
}
} |
Output:
30
Example 2:
object Main{
def main(args : Array[String])
{
val message = "hello "
implicit val name = "world!"
def disp( implicit nm : String) = message + nm
// Implicit parameter will be passed here
val result = disp
// Implicit parameters will not be passed
val result 2 = disp( "GFG!" )
println( "With Implicit parameters:" )
println(result)
println( "Without Implicit parameters:" )
println(result 2 )
}
} |
Output
With Implicit parameters: hello world! Without Implicit parameters: hello GFG!