Back to Scala3

E135: Stable Identifier Pattern

docs/_docs/reference/error-codes/E135.md

3.8.41.6 KB
Original Source

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

scala
def example(a: Any) =
  var x = 1
  a match
    case `x` => "matched x"
    case _ => "other"

Error

scala
-- [E135] Type Error: example.scala:4:9 ----------------------------------------
4 |    case `x` => "matched x"
  |         ^^^
  |         Stable identifier required, but `x` found

Solution

scala
// 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"
scala
// 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"
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>