E010: Top Level Implicit Class

Note: This error code was made inactive in Scala 3.2.0. Implicit classes are now allowed at the top level.

This error occurred in earlier versions of Scala 3 when an implicit class was defined at the top level of a file, rather than being nested inside an object, class, or package object.

In Scala 2 and early Scala 3, implicit classes had to be defined inside another definition (such as an object or package object) to prevent potential issues with implicit resolution and scope. This restriction was later lifted in Scala 3.2.0.


Example (Scala 3.0.x - 3.1.x)

// Top-level implicit class - not allowed in Scala 3.0-3.1
implicit class RichInt(val x: Int) {
  def square: Int = x * x
}

Error

-- [E010] Syntax Error: example.scala:2:0 ------------------------------------
2 |implicit class RichInt(val x: Int) {
  |^
  |An implicit class may not be top-level

Solution (Scala 3.0.x - 3.1.x)

// Wrap in an object
object Extensions {
  implicit class RichInt(val x: Int) {
    def square: Int = x * x
  }
}

// Usage
import Extensions._
val result = 5.square
// Or use a package object
package object mypackage {
  implicit class RichInt(val x: Int) {
    def square: Int = x * x
  }
}

Solution (Scala 3.2.0+)

// Top-level implicit classes are now allowed
implicit class RichInt(val x: Int) {
  def square: Int = x * x
}

// However, prefer using extension methods in Scala 3
extension (x: Int)
  def square: Int = x * x