Implicit Parameters In Scala

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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) 
          
    }
}

chevron_right



Output:

30

Example 2:

Scala

filter_none

edit
close

play_arrow

link
brightness_4
code

object Main{
      
    def main(args: Array[String])
    {
        val message = "hello "
        implicit val name = "world!"
        def disp(implicit nm : String) = message + nm
          
        // Implicit parameter wiil be passed here
        val result = disp
          
        // Implicit parameters will not be passed
        val result2 = disp("GFG!"
        println("With Implicit parameters:")
        println(result) 
        println("Without Implicit parameters:")
        println(result2)     
    }
}

chevron_right



Output

With Implicit parameters:
hello world!
Without Implicit parameters:
hello GFG!



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.