Scala匿名模式匹配函数赋值MyFunction的编译机制疑问
Great question! Let's break down the mechanism behind this behavior step by step.
The Core Reason: SAM Conversion for Pattern-Matching Anonymous Functions
Scala has a special compiler rule for anonymous pattern-matching functions (the { case ... } syntax) when they’re assigned to a Single Abstract Method (SAM) type—a trait or abstract class with exactly one unimplemented method.
Here’s how it works for your f1 example:
trait MyFunction { def map(value: String): String } // This compiles successfully val f1: MyFunction = { case e: String => e.toLowerCase() }
When the compiler processes this assignment, it doesn’t first convert the pattern-matching function to a Function or PartialFunction. Instead, it directly generates an anonymous instance of MyFunction, where the map method’s implementation wraps the pattern-matching logic. This is equivalent to writing:
val f1: MyFunction = new MyFunction { def map(value: String): String = value match { case e: String => e.toLowerCase() } }
Since your pattern matches all valid String inputs, this implementation is total and fully compliant with MyFunction’s contract.
Why f2 and f3 Fail to Compile
When you first assign the pattern-matching function to a Function[String, String] or PartialFunction[String, String], the compiler converts it to a concrete instance of that specific standard library type:
val f: Function[String, String] = { case e: String => e.toLowerCase() } val pf: PartialFunction[String, String] = { case e: String => e.toLowerCase() }
These objects are now locked into their standard library types, which share no inheritance or implicit conversion with your custom MyFunction trait. Without a custom conversion, Scala can’t bridge this type gap, leading to the error you encountered:
Expression of type Function[String, String] doesn't conform to expected type MyFunction
Clarification on the Scala Specification
The Scala 2.11 spec notes that anonymous pattern-matching functions can target Function or PartialFunction—but this isn’t an exclusive list. The spec highlights the most common use cases, but the underlying rule extends to any SAM type where the abstract method’s signature aligns with the pattern-matching function’s input/output types. This behavior stays consistent across Scala 2.11, 2.12, and 2.13 because SAM conversion for pattern-matching functions is a foundational compiler feature.
内容的提问来源于stack exchange,提问作者Vladimir Prus

