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:
Scala
object Main{
def main(args : Array[String])
{
val value = 10
implicit val multiplier = 3
def multiply( implicit by : Int) = value * by
val result = multiply
println(result)
}
}
|
Output:
30
Example 2:
Scala
object Main{
def main(args : Array[String])
{
val message = "hello "
implicit val name = "world!"
def disp( implicit nm : String) = message + nm
val result = disp
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!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!