Implicit Parameters in Scala

Scala | Implicit Parameters: Here, we will learn about the implicit parameters and their functioning with examples.
Submitted by Shivang Yadav, on July 20, 2020

Implicit parameters are special parameters of a method. An easy definition would be "a predefined value that can be used when no value is passed as a parameter to the function."

In Scala, a method can have implicit parameters that will have the implicit keyword as a prefix. There can be multiple implicit parameters in a method defined using a single implicit keyword and a mix of implicit and normal parameters can also be possible.

If we define an implicit parameter for a method in Scala. There can be two cases:

  • Case 1 (when a value is passed to the function): In this case, the method will use the passed value to perform the operation it was intended to do.
  • Case 2 (when no value is passed to the function): In this case, the method will look for an implicit value of the required type. If a matched value is found the compiler will pass it to the method automatically.

Syntax:

Function with one implicit parameter:

def function_name (implicit value : type) 

Function with multiple implicit parameters:

def function_name (implicit value1 : type, value2 : type)

Function with mix of implicit and regular parameters:

def function_name (value1 : type)(implicit value2 : type)

Now, let's see a few examples to understand the working of implicit parameters in Scala.

Example1: Using a simple implicit function

// Program to illustrate the working 
// of implicit parameters 
object MyClass {
    // conversionValue which will be taken using API 
    val conversionValue = 74.93; 
    implicit val x : Float = 100
    
    def usdToInrConvertor(implicit usd : Float)={
        val inr = (usd*conversionValue).asInstanceOf[Float] 
        println(f"$usd dollars = $inr Rupees")
   }

    def main(args: Array[String]) {
        println("Calling method with implicit parameter by passing a value ")
        usdToInrConvertor(50)
        println("Calling method with implicit parameter without passing a value ")
        usdToInrConvertor
    }
}

Output:

Calling method with implicit parameter by passing a value 
50.0 dollars = 3746.5 Rupees
Calling method with implicit parameter without passing a value 
100.0 dollars = 7493.0 Rupees

In the above code, we have created a method named usdToInrConvertor() that is used to convert USD to INR. The method takes a parameter USD for the value of US dollars to be converted. This value is implicit.

When we passed value to the method, it used the value (50) for the conversion and displays the result. And when we pass nothing to the method, it looks for an implicit value which will be used.

Example 2: Using a function with a mix of implicit and regular parameters

// program to demonstrate function with 
// mix of implicit and regular parameters
object MyClass {
    implicit val fullTank : Float = 18
    
    def mileageCal(distance: Float)(implicit fuel : Float)= {
        val mileage = (distance/fuel).asInstanceOf[Float]
        println(f"The bike covered $distance KM in $fuel liters of fuel and gave the milage of $mileage Km/L")
    }
    
    def main(args: Array[String]) {
        println("Calling method with implicit parameter by passing a value ")
        mileageCal(423)(12.5f)
        println("Calling method with implicit parameter without passing a value ")
        mileageCal(541)
    }
}

Output:

Calling method with implicit parameter by passing a value 
The bike covered 423.0 KM in 12.5 liters of fuel and gave the milage of 33.84 Km/L
Calling method with implicit parameter without passing a value 
The bike covered 541.0 KM in 18.0 liters of fuel and gave the milage of 30.055555 Km/L

In the above code, we have created a method name milageCal() which will calculate the mileage of a vehicle using the distance it traveled and fuel it has with are passed to the function as parameters. The fuel is an implicit parameter. Then we have called the method with and without passing the value for fuel. And the function printed proper value in both cases.

Example 3: Using a function with multiple implicit parameters

// Program to demonstrate function 
// multiple implicit parameters
object MyClass {
    implicit val baseSal : Float = 5000
    implicit val baseExp : Int = 0
    
    def salaryCal(implicit lastSalary : Float, exp: Int)= {
        val salary = lastSalary + (lastSalary*(exp)*0.15)
        println(f"The salary of employee is $salary")
    }
    
    def main(args: Array[String]) {
        println("Calling method with implicit parameter by passing a value ")
        salaryCal(15000.00F, 4)
        println("Calling method with implicit parameter without passing a value ")
        salaryCal
    }
}

Output:

Calling method with implicit parameter by passing a value 
The salary of employee is 24000.0
Calling method with implicit parameter without passing a value 
The salary of employee is 5000.0

In the above code, we have created a method named salaryCal() that calculates the salary for a new employee at a company. The method takes multiple implicit parameters as lastSalary and exp which are used for calculations. Then we have called the method with and without passing the value for these parameters. And the function printed proper value in both cases.

Points to be noted for example:

  1. If we are passing multiple implicit values, then the type of both should be different
  2. While calling we need to either call with both parameters or without any parameter.

Note:

  • We have used asInstanceof[] method for type casting from double (the result will be of double type) to float. I know it might lead to data losses but float precision is ok for me.
  • To print output we have done string interpolation using f method of StringContext class.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.