Implicits in Scala

Posted April 12, 2023 by Rohith ‐ 2 min read

Implicits in Scala are a powerful mechanism for providing additional parameters or conversions to a method or function without explicitly passing them in as arguments. They can be used to make code more concise and easier to read.

Here are some examples of how to use implicits in Scala:

Implicit Parameters

You can define a parameter as implicit in a method or function, which means that it will be automatically supplied by the compiler when the method or function is called. Here’s an example:

def greet(name: String)(implicit greeting: String) = println(s"$greeting, $name!")
implicit val hello = "Hello"
greet("John")

In this example, we define a method greet that takes a name parameter and an implicit greeting parameter. When we call the method with greet(“John”), the compiler will automatically supply the implicit parameter hello, which is of type String, to the method. The output will be Hello, John!.

Implicit Conversions

You can define an implicit conversion to convert a value of one type to another type. Here’s an example:

implicit def intToString(i: Int): String = i.toString
val str: String = 123

In this example, we define an implicit conversion from Int to String using a method named intToString. We can then assign an Int value of 123 to a variable of type String and the compiler will automatically apply the conversion. The resulting str variable will have the value “123”.

Implicit Classes

You can define an implicit class to add methods to an existing class. Here’s an example:

implicit class RichInt(i: Int) {
  def squared: Int = i * i
}
val x = 3
val y = x.squared

In this example, we define an implicit class named RichInt that takes an Int parameter and adds a squared method to it. We can then call the squared method on an Int value and the compiler will automatically convert the Int value to a RichInt object and apply the method. The resulting y variable will have the value 9.

These are just a few examples of how to use implicits in Scala. They are a powerful feature that can greatly simplify your code, but they should be used judiciously to avoid confusion and make your code more readable.

quick-references scala implicits blog scala-implicits

Subscribe For More Content