Skip to Content
Course content

134: Match Types in Scala 3

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

You've probably spent a lot of time using match expressions to handle values. But Scala 3 introduces something that looks similar but happens at a completely different stage of the process: Match Types. Instead of branching on a value at runtime, we're branching on a type at compile time. Think of it as a function that takes a type as an input and returns a type as an output.

What's the actual difference between a value match and a match type?

It's a subtle but massive distinction. A regular match is a value-level operation; the program runs, checks what's inside a variable, and picks a path. A match type is a type-level operation. The compiler looks at the type you've provided and "computes" the resulting type before the code even runs.

I like to think of it as a mapping. If I tell the compiler "I'm giving you an Int," the match type might say, "Okay, then the result must be a String." If I give it a Boolean, it might say, "Then the result is an Int." There is no runtime overhead here because the decision is baked into the bytecode.

How do I actually write one of these?

The syntax is surprisingly intuitive if you're already comfortable with pattern matching. You define a type alias that uses the match keyword. Let's look at a real-world scenario: imagine you're building a data transformer where different input types require different internal representation types.

type InternalRep[T] = T match {
  case Int    => Long
  case String => java.util.UUID
  case Boolean => Int
  case _      => Any
}

// Now let's see it in action
val a: InternalRep[Int] = 10L      // This is actually a Long
val b: InternalRep[String] = java.util.UUID.randomUUID() // This is a UUID
val c: InternalRep[Boolean] = 1    // This is an Int

Notice that InternalRep[Int] isn't a generic container like List[Int]; it literally becomes Long. If you hover over those variables in your IDE, you'll see the compiler has already resolved them to their final types.

Can I use this to make my methods return different types based on the input?

Yes, and this is where match types actually become useful in a large codebase. Without match types, if you wanted a method to return a Long when passed an Int and a UUID when passed a String, you'd probably be forced to return Any and use a lot of messy casting.

With match types, you can keep your API type-safe. I'll show you how to integrate it into a class:

class DataConverter {
  type ResultType[T] = T match {
    case Int    => Long
    case String => java.util.UUID
    case _      => String
  }

  def convert[T](input: T): ResultType[T] = input match {
    case i: Int    => i.toLong
    case s: String => java.util.UUID.fromString(s)
    case _         => input.toString
  }
}

val converter = new DataConverter()
val res1 = converter.convert(42)       // Compiler knows res1 is Long
val res2 = converter.convert("abc-123") // Compiler knows res2 is UUID

One thing to watch out for: you usually need to pair the match type with a standard value-level match inside the method body. The match type handles the signature (the "what"), while the value match handles the implementation (the "how").

Is this just a more complex version of a Type Class?

Not really. They solve different problems. A type class (like Numeric[T]) is about adding behavior to a type. Match types are about transforming one type into another.

If you find yourself wanting to say "If the type is X, then the associated type must be Y," use a match type. If you want to say "I don't care what the type is, as long as it knows how to add itself to another instance of the same type," use a type class. I've seen developers try to force match types to do everything, but that leads to a "type-level spaghetti" that's a nightmare to maintain. Keep them separate.




📋 Practical Task

Implement a Type-Safe API Response Mapper

You are building a client library that handles different types of API responses. Depending on the request type, the response body should be a different Scala type.

Requirements:

  • Create a match type called ResponseBody[T].
  • If T is String (representing a 'User' request), ResponseBody should be Int (the User ID).
  • If T is Int (representing a 'Post' request), ResponseBody should be String (the Post content).
  • For any other type, ResponseBody should be Boolean.
  • Implement a class ApiClient with a method fetch[T](request: T): ResponseBody[T] that returns a dummy value matching the computed type.

Verification: Ensure that when you call fetch("UserRequest"), the resulting variable is inferred as an Int without any explicit casting.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.