[Scala] Implicit Parameters

mj park
2 min readJan 10, 2022

Overview

I will go over a simple example of “implicit conversion” in Scala. More details can be found from the original article from the official Scala documentation.

Implicit Parameters

An implicit parameter is a parameter with a keyword “implicit” in a method. If the parameter is not passed, Scala will try to get an implicit value of the correct type. It will look at two places

  1. Scala will first look if there is any definition of the implicit parameter that can be directly accessed at the point the method with the implicit parameter is called
  2. Then, it will look for members marked “implicit” with the candidate type in all the companion objects

Example

abstract class Monoid[A] {
def add(x: A, y: A): A
def unit: A
}
object ImplicitTest {
implicit val stringMonoid: Monoid[String] = new Monoid[String] {
def add(x: String, y: String): String = x concat y
def unit: String = ""
}

implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
def add(x: Int, y: Int): Int = x + y
def unit: Int = 0
}

def sum[A](xs: List[A])(implicit m: Monoid[A]): A =
if (xs.isEmpty) m.unit
else m.add(xs.head, sum(xs.tail))

def main(args: Array[String]): Unit = {
// 1. uses intMonoid implicitly
println(sum(List(1, 2, 3)))
// 2. uses stringMonoid implicitly
println(sum(List("a", "b", "c")))
}
}

When sum is called with integer list, it passes a List[Integer] for xs, which means that the type parameter A is Integer in that call. From there, Scala will look for an implicit of type Monoid[Integer]. Remember the first rule?

Scala will first look if there is any definition of the implicit parameter that can be directly accessed at the point the method with the implicit parameter is called

Since intMonoid can be directly accessed from main and is a correct type ofMonoid[A], it is passed to the sum automatically.

// calling sum with integer lists
sum(List(1,2,3)
// this calls `sum` as follows
sum[Integer](xs: List[Integer])(implicit m: Monoid[Integer])
// Since intMonoid is available in the scope of the call and is the correct type, it will be passedsum[Integer](List(1,2,3)(intMonoid)// sum will use the implemented "add" from intMonoid and print
6

--

--

mj park

Software Engineer | Scala | Functional Programming