Skip to Content
Course content

199: Implicit Resolution Rules In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've spent more time than I'd like to admit fighting with the Scala compiler because it couldn't find an implicit I *knew* was right there, or worse, it found two and didn't know which one to pick. To really get a handle on how the compiler thinks, we need to stop guessing and start poking at the resolution rules.

Let's build a tiny type class for JSON encoding. We'll have a JsonEncoder[T] and a User case class. This is the perfect playground because we can place implicits in several different scopes to see who wins the "priority war."

trait JsonEncoder[T] {
  def encode(value: T): String
}

case class User(name: String, age: Int)

object JsonEncoder {
  // A generic fallback for anything that has a toString
  implicit def genericEncoder[T]: JsonEncoder[T] = new JsonEncoder[T] {
    def encode(value: T): String = s"""{"value": "${value.toString}"}"""
  }
}

def printJson[T](value: T)(implicit encoder: JsonEncoder[T]): Unit = {
  println(encoder.encode(value))
}

The Baseline and the Generic Fallback

Right now, if I call printJson(User("Alice", 30)), it works. But it's using the genericEncoder defined in the JsonEncoder companion object. I don't want a generic string; I want a proper JSON object for my User.

The first thing I'll try is putting a specific encoder in the companion object of the User class. This is the most common pattern in Scala.

object User {
  implicit val userEncoder: JsonEncoder[User] = new JsonEncoder[User] {
    def encode(user: User): String = s"""{"name": "${user.name}", "age": ${user.age}}"""
  }
}

Now, when I run printJson(User("Alice", 30)), I get the specific JSON. The compiler ignored the generic one in JsonEncoder and picked the one in User. This tells us an important rule: the companion object of the type being searched for (User) has higher priority than the companion object of the type class trait (JsonEncoder).

Testing Local Overrides

But what if I'm in a specific part of my app where I need a different format for User—maybe a "minimal" version? I'll define an implicit right inside the method where I'm calling printJson.

def processUser(user: User): Unit = {
  implicit val minimalUserEncoder: JsonEncoder[User] = new JsonEncoder[User] {
    def encode(user: User): String = s"""{"n": "${user.name}"}"""
  }
  
  printJson(user)
}

I just ran this, and it used the minimalUserEncoder. The User companion object was completely ignored. This confirms that local scope (the current block or class) always beats companion objects. It's the most "specific" place the compiler looks, so it wins.

The Import Conflict

Now let's complicate things. Suppose I have a legacy module with its own encoders, and I import them.

object LegacyEncoders {
  implicit val legacyUserEncoder: JsonEncoder[User] = new JsonEncoder[User] {
    def encode(user: User): String = s"LEGACY: ${user.name}"
  }
}

If I add import LegacyEncoders._ to my file and call printJson(user) without that local minimalUserEncoder, which one wins? The User companion or the import?

I'll try it... and the result is the User companion. Wait, that's interesting. Even though I explicitly imported LegacyEncoders, the companion object of the type User still took precedence. The hierarchy is starting to look like this: Local Scope > Imported Scope > Companion Object of the Type > Companion Object of the Trait.

Triggering the Ambiguity Error

Finally, let's see where the compiler gives up. What happens if I have two implicits in the *same* priority level? I'll define another implicit in the local scope.

def chaosUser(user: User): Unit = {
  implicit val encoderA: JsonEncoder[User] = new JsonEncoder[User] {
    def encode(u: User): String = "A"
  }
  implicit val encoderB: JsonEncoder[User] = new JsonEncoder[User] {
    def encode(u: User): String = "B"
  }
  
  printJson(user) // This will fail to compile
}

The compiler throws an "ambiguous implicit values" error. It doesn't matter that encoderA was defined first; since they are both in the local scope, they have equal priority. The compiler refuses to guess and forces you to be explicit.

  • Local Scope: The immediate block, method, or class. Highest priority.
  • Import Scope: Values brought in via import.
  • Companion of the Type: The object User for JsonEncoder[User].
  • Companion of the Trait: The object JsonEncoder for JsonEncoder[T]. Lowest priority.



📋 Practical Task

Fixing the Ambiguous User Encoder

You are working on a project where two different libraries provide implicit JsonEncoder[User] instances. Both are being imported into the same service class, causing a compilation error because the compiler cannot decide which one to use.

The Scenario:

trait JsonEncoder[T] {
  def encode(value: T): String
}

case class User(name: String)

object LibraryA {
  implicit val encoder: JsonEncoder[User] = new JsonEncoder[User] {
    def encode(u: User): String = s"LibA: ${u.name}"
  }
}

object LibraryB {
  implicit val encoder: JsonEncoder[User] = new JsonEncoder[User] {
    def encode(u: User): String = s"LibB: ${u.name}"
  }
}

class UserService {
  import LibraryA._
  import LibraryB._

  def render(user: User): Unit = {
    // This line causes an "ambiguous implicit values" error
    printJson(user)
  }
}

def printJson[T](value: T)(implicit encoder: JsonEncoder[T]): Unit = {
  println(encoder.encode(value))
}

Your Task: Modify the render method in UserService so that it specifically uses the encoder from LibraryB, without removing the imports from the class. Apply the rule of "local scope priority" to resolve the conflict.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.