Back to Scala3

E011: Implicit Case Class

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

3.8.41.8 KB
Original Source

E011: Implicit Case Class

This error is emitted when a case class is defined with the implicit modifier. Case classes cannot be implicit in Scala.

Case classes automatically generate companion objects and various methods (like apply, unapply, copy, etc.) that would conflict with implicit class semantics.

If you want implicit conversions, use a plain implicit class instead.


Example

scala
implicit case class Wrapper(value: String)

Error

scala
-- [E011] Syntax Error: example.scala:1:20 -------------------------------------
1 |implicit case class Wrapper(value: String)
  |^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |A case class may not be defined as implicit
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Implicit classes may not be case classes. Instead use a plain class:
  |
  | implicit class Wrapper...
   -----------------------------------------------------------------------------

Solution

scala
// Use a regular implicit class
object Implicits:
  implicit class Wrapper(val value: String):
    def doubled: String = value + value

import Implicits.*
val result = "hello".doubled
scala
// In Scala 3, prefer extension methods over implicit classes
extension (value: String)
  def doubled: String = value + value

val result = "hello".doubled
<!-- 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>