Back to Scala3

E162: Case Class In Inlined Code

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

3.8.41.8 KB
Original Source

E162: Case Class In Inlined Code

This error occurs when a case class or case object is defined inside an inline method or quoted code block.

Case class definitions generate a significant amount of bytecode (including apply, unapply, copy, equals, hashCode, toString, and other methods). Inlining such definitions would multiply this bytecode footprint at every call site, leading to excessive code bloat.


Example

scala
inline def example = {
  case class Data(x: Int)
  Data(42)
}

Error

scala
-- [E162] Syntax Error: example.scala:2:13 -------------------------------------
2 |  case class Data(x: Int)
  |  ^^^^^^^^^^^^^^^^^^^^^^^
  |Case class definitions are not allowed in inline methods or quoted code. Use a normal class instead.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Case class/object definitions generate a considerable footprint in code size.
  | Inlining such definition would multiply this footprint for each call site.
   -----------------------------------------------------------------------------

Solution

scala
// Define case class outside the inline method
case class Data(x: Int)

inline def example = Data(42)
scala
// Or use a regular class inside the inline method
inline def example = {
  class Data(val x: Int)
  new Data(42)
}
<!-- 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>