E135: Stable Identifier Pattern
This error occurs when using a non-stable identifier in a pattern match where a stable identifier is required.
In Scala pattern matching, when you use backticks to match against an existing value (e.g., `x`), the referenced identifier must be stable. A stable identifier is one whose value cannot change, such as a val, an object, or a stable path. Mutable variables (var) are not stable identifiers because their values can change.
Using a mutable variable in a pattern would be problematic because the value being matched against could change during or after the match, leading to inconsistent behavior.
Example
def example(a: Any) =
var x = 1
a match
case `x` => "matched x"
case _ => "other"
Error
-- [E135] Type Error: example.scala:4:9 ----------------------------------------
4 | case `x` => "matched x"
| ^^^
| Stable identifier required, but `x` found
Solution
// Use a val instead of a var for the stable identifier
def example(a: Any) =
val x = 1
a match
case `x` => "matched x"
case _ => "other"
// Alternative: Use a guard condition instead of stable identifier
def example(a: Any) =
var x = 1
a match
case y if y == x => "matched x"
case _ => "other"
In this article