[scala] Understanding implicit in Scala

I was making my way through the Scala playframework tutorial and I came across this snippet of code which had me puzzled:

def newTask = Action { implicit request =>
taskForm.bindFromRequest.fold(
        errors => BadRequest(views.html.index(Task.all(), errors)),
        label => {
          Task.create(label)
          Redirect(routes.Application.tasks())
        } 
  )
}

So I decided to investigate and came across this post.

I still don't get it.

What is the difference between this:

implicit def double2Int(d : Double) : Int = d.toInt

and

def double2IntNonImplicit(d : Double) : Int = d.toInt

other than the obvious fact they have different method names.

When should I use implicit and why?

This question is related to scala syntax playframework keyword

The answer is


Also, in the above case there should be only one implicit function whose type is double => Int. Otherwise, the compiler gets confused and won't compile properly.

//this won't compile

implicit def doubleToInt(d: Double) = d.toInt
implicit def doubleToIntSecond(d: Double) = d.toInt
val x: Int = 42.0

I had the exact same question as you had and I think I should share how I started to understand it by a few really simple examples (note that it only covers the common use cases).

There are two common use cases in Scala using implicit.

  • Using it on a variable
  • Using it on a function

Examples are as follows

Using it on a variable. As you can see, if the implicit keyword is used in the last parameter list, then the closest variable will be used.

// Here I define a class and initiated an instance of this class
case class Person(val name: String)
val charles: Person = Person("Charles")

// Here I define a function
def greeting(words: String)(implicit person: Person) = person match {
  case Person(name: String) if name != "" => s"$name, $words"
    case _ => "$words"
}

greeting("Good morning") // Charles, Good moring

val charles: Person = Person("")
greeting("Good morning") // Good moring

Using it on a function. As you can see, if the implicit is used on the function, then the closest type conversion method will be used.

val num = 10 // num: Int (of course)

// Here I define a implicit function
implicit def intToString(num: Int) = s"$num -- I am a String now!"

val num = 10 // num: Int (of course). Nothing happens yet.. Compiler believes you want 10 to be an Int

// Util...
val num: String = 10 // Compiler trust you first, and it thinks you have `implicitly` told it that you had a way to covert the type from Int to String, which the function `intToString` can do!
// So num is now actually "10 -- I am a String now!"
// console will print this -> val num: String = 10 -- I am a String now!

Hope this can help.


WARNING: contains sarcasm judiciously! YMMV...

Luigi's answer is complete and correct. This one is only to extend it a bit with an example of how you can gloriously overuse implicits, as it happens quite often in Scala projects. Actually so often, you can probably even find it in one of the "Best Practice" guides.

object HelloWorld {
  case class Text(content: String)
  case class Prefix(text: String)

  implicit def String2Text(content: String)(implicit prefix: Prefix) = {
    Text(prefix.text + " " + content)
  }

  def printText(text: Text): Unit = {
    println(text.content)
  }

  def main(args: Array[String]): Unit = {
    printText("World!")
  }

  // Best to hide this line somewhere below a pile of completely unrelated code.
  // Better yet, import its package from another distant place.
  implicit val prefixLOL = Prefix("Hello")
}

In scala implicit works as:

Converter

Parameter value injector

Extension method

There are 3 types of use of Implicit

  1. Implicitly type conversion : It converts the error producing assignment into intended type

    val x :String = "1"
    
    val y:Int = x
    

String is not the sub type of Int , so error happens in line 2. To resolve the error the compiler will look for such a method in the scope which has implicit keyword and takes a String as argument and returns an Int .

so

implicit def z(a:String):Int = 2

val x :String = "1"

val y:Int = x // compiler will use z here like val y:Int=z(x)

println(y) // result 2  & no error!
  1. Implicitly receiver conversion: We generally by receiver call object's properties, eg. methods or variables . So to call any property by a receiver the property must be the member of that receiver's class/object.

     class Mahadi{
    
     val haveCar:String ="BMW"
    
     }
    

    class Johnny{

    val haveTv:String = "Sony"

    }

   val mahadi = new Mahadi



   mahadi.haveTv // Error happening

Here mahadi.haveTv will produce an error. Because scala compiler will first look for the haveTv property to mahadi receiver. It will not find. Second it will look for a method in scope having implicit keyword which take Mahadi object as argument and returns Johnny object. But it does not have here. So it will create error. But the following is okay.

class Mahadi{

val haveCar:String ="BMW"

}

class Johnny{

val haveTv:String = "Sony"

}

val mahadi = new Mahadi

implicit def z(a:Mahadi):Johnny = new Johnny

mahadi.haveTv // compiler will use z here like new Johnny().haveTv

println(mahadi.haveTv)// result Sony & no error
  1. Implicitly parameter injection: If we call a method and do not pass its parameter value, it will cause an error. The scala compiler works like this - first will try to pass value, but it will get no direct value for the parameter.

     def x(a:Int)= a
    
     x // ERROR happening
    

Second if the parameter has any implicit keyword it will look for any val in the scope which have the same type of value. If not get it will cause error.

def x(implicit a:Int)= a

x // error happening here

To slove this problem compiler will look for a implicit val having the type of Int because the parameter a has implicit keyword.

def x(implicit a:Int)=a

implicit val z:Int =10

x // compiler will use implicit like this x(z)
println(x) // will result 10 & no error.

Another example:

def l(implicit b:Int)

def x(implicit a:Int)= l(a)

we can also write it like-

def x(implicit a:Int)= l

Because l has a implicit parameter and in scope of method x's body, there is an implicit local variable(parameters are local variables) a which is the parameter of x, so in the body of x method the method-signature l's implicit argument value is filed by the x method's local implicit variable(parameter) a implicitly.

So

 def x(implicit a:Int)= l

will be in compiler like this

def x(implicit a:Int)= l(a)

Another example:

def c(implicit k:Int):String = k.toString

def x(a:Int => String):String =a

x{
x => c
}

it will cause error, because c in x{x=>c} needs explicitly-value-passing in argument or implicit val in scope.

So we can make the function literal's parameter explicitly implicit when we call the method x

x{
implicit x => c // the compiler will set the parameter of c like this c(x)
}

This has been used in action method of Play-Framework

in view folder of app the template is declared like
@()(implicit requestHreader:RequestHeader)

in controller action is like

def index = Action{
implicit request =>

Ok(views.html.formpage())  

}

if you do not mention request parameter as implicit explicitly then you must have been written-

def index = Action{
request =>

Ok(views.html.formpage()(request))  

}
  1. Extension Method

Think, we want to add new method with Integer object. The name of the method will be meterToCm,

> 1 .meterToCm 
res0 100 

to do this we need to create an implicit class within a object/class/trait . This class can not be a case class.

object Extensions{
    
    implicit class MeterToCm(meter:Int){
        
        def  meterToCm={
             meter*100
        }

    }

}

Note the implicit class will only take one constructor parameter.

Now import the implicit class in the scope you are wanting to use

import  Extensions._

2.meterToCm // result 200

Why and when you should mark the request parameter as implicit:

Some methods that you will make use of in the body of your action have an implicit parameter list like, for example, Form.scala defines a method:

def bindFromRequest()(implicit request: play.api.mvc.Request[_]): Form[T] = { ... }

You don't necessarily notice this as you would just call myForm.bindFromRequest() You don't have to provide the implicit arguments explicitly. No, you leave the compiler to look for any valid candidate object to pass in every time it comes across a method call that requires an instance of the request. Since you do have a request available, all you need to do is to mark it as implicit.

You explicitly mark it as available for implicit use.

You hint the compiler that it's "OK" to use the request object sent in by the Play framework (that we gave the name "request" but could have used just "r" or "req") wherever required, "on the sly".

myForm.bindFromRequest()

see it? it's not there, but it is there!

It just happens without your having to slot it in manually in every place it's needed (but you can pass it explicitly, if you so wish, no matter if it's marked implicit or not):

myForm.bindFromRequest()(request)

Without marking it as implicit, you would have to do the above. Marking it as implicit you don't have to.

When should you mark the request as implicit? You only really need to if you are making use of methods that declare an implicit parameter list expecting an instance of the Request. But to keep it simple, you could just get into the habit of marking the request implicit always. That way you can just write beautiful terse code.


A very basic example of Implicits in scala.

Implicit parameters:

val value = 10
implicit val multiplier = 3
def multiply(implicit by: Int) = value * by
val result = multiply // implicit parameter wiil be passed here
println(result) // It will print 30 as a result

Note: Here multiplier will be implicitly passed into the function multiply. Missing parameters to the function call are looked up by type in the current scope meaning that code will not compile if there is no implicit variable of type Int in the scope.

Implicit conversions:

implicit def convert(a: Double): Int = a.toInt
val res = multiply(2.0) // Type conversions with implicit functions
println(res)  // It will print 20 as a result

Note: When we call multiply function passing a double value, the compiler will try to find the conversion implicit function in the current scope, which converts Int to Double (As function multiply accept Int parameter). If there is no implicit convert function then the compiler will not compile the code.


Examples related to scala

Intermediate language used in scalac? Why does calling sumr on a stream with 50 tuples not complete Select Specific Columns from Spark DataFrame Joining Spark dataframes on the key Provide schema while reading csv file as a dataframe how to filter out a null value from spark dataframe Fetching distinct values on a column using Spark DataFrame Can't push to the heroku Spark - Error "A master URL must be set in your configuration" when submitting an app Add jars to a Spark Job - spark-submit

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to playframework

Error: Argument is not a function, got undefined Understanding implicit in Scala How do I change the default port (9000) that Play uses when I execute the "run" command?

Examples related to keyword

How to select data from 30 days? How to use "raise" keyword in Python Python: SyntaxError: keyword can't be an expression Understanding implicit in Scala How do I create sql query for searching partial matches? What is the native keyword in Java for? Difference between "this" and"super" keywords in Java Equivalent of "continue" in Ruby What is the equivalent of the C# 'var' keyword in Java? Is there a goto statement in Java?