Back to Scala3

E197: Inlined Anonymous Class Warning

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

3.8.41.9 KB
Original Source

E197: Inlined Anonymous Class Warning

This warning is emitted when an inline method creates an anonymous class. Since inline methods are expanded at each call site, the anonymous class definition will be duplicated in the generated bytecode, potentially leading to a large number of classfiles.


Longer explanation:

Anonymous class will be defined at each use site, which may lead to a larger number of classfiles.

To inline class definitions, you may provide an explicit class name to avoid this warning.


Example

scala
inline def createObject(): Object =
  new Object {}

Error

scala
-- [E197] Potential Issue Warning: example.scala:2:2 ---------------------------
2 |  new Object {}
  |  ^
  |  New anonymous class definition will be duplicated at each inline site
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Anonymous class will be defined at each use site, which may lead to a larger number of classfiles.
  |
  | To inline class definitions, you may provide an explicit class name to avoid this warning.
   -----------------------------------------------------------------------------

Solution

Use a named class inside the inline method:

scala
inline def createObject(): Object =
  class NamedClass extends Object
  new NamedClass

Or define the class outside the inline method:

scala
class MyObject extends Object

inline def createObject(): Object =
  new MyObject
<!-- 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>