0 votes
in Scala Constructs by
Explain Implicit Parameter.

1 Answer

0 votes
by

The implicit parameter, as opposed to the regular parameter, can be passed silently to a method without going through the regular parameter list. The implicit keyword indicates these parameters and any parameters following the implicit keyword are implicit. Essentially, when we don't pass anything to methods or functions, the compiler will look for an implicit value and use that as a parameter. Whenever implicit keywords appear in a function's parameter scope, this marks all parameters as implicit. Each method can simply have a single implicit keyword. 

Syntax:

def func1(implicit a : Int)                                                   // a is implicit 

def func2(implicit a : Int, b : Int)                                        //  a and b both are implicit 

def func3 (a : Int)(implicit b : Int)                                      // only b is implicit  

Example: 

 object InterviewBit 

   def main(args: Array[String])  

   { 

      val value = 20 

      implicit val addition = 5 

      def add(implicit to: Int) = value + to 

      val result = add 

      println(result)  

   } 

}  

Output: 

 25 

...