Back to Scala3

E065: Traits May Not Be Final

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

3.8.41.6 KB
Original Source

E065: Traits May Not Be Final

This error is emitted when a trait is declared with the final modifier.

A trait can never be final since it is abstract by nature and must be extended or mixed in to be useful. The final modifier prevents inheritance, which contradicts the purpose of a trait.


Example

scala
final trait MyTrait

Error

scala
-- [E065] Syntax Error: example.scala:1:12 -------------------------------------
1 |final trait MyTrait
  |            ^
  |            trait MyTrait may not be final
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | A trait can never be final since it is abstract and must be extended to be useful.
   -----------------------------------------------------------------------------

Solution

scala
// Remove final from trait definitions
trait MyTrait:
  def method: Int
scala
// If you want a final implementation, use a final class
final class MyFinalClass:
  def method: Int = 42
scala
// Or use a sealed trait if you want to restrict implementations
sealed trait MyTrait
final class Implementation extends MyTrait
<!-- 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>