In Scala 3, you declare a class open
for OOP-style extension (as opposed to extension
).
➜ scalac -d /tmp mycase.scala badkext.scala
➜ scalac -source future -d /tmp mycase.scala badkext.scala
there were 1 feature warning(s); re-run with -feature for details
➜ scalac -feature -source future -d /tmp mycase.scala badkext.scala
-- Feature Warning: badkext.scala:2:23 ----------------------------------------------------------------------------------------------------------
2 |class SpecialK extends K(27)
| ^^^^^
| Unless class K is declared 'open', its extension in a separate file should be enabled
| by adding the import clause 'import scala.language.adhocExtensions'
| or by setting the compiler option -language:adhocExtensions.
| See the Scala docs for value scala.language.adhocExtensions for a discussion
| why the feature should be explicitly enabled.
1 warning found
➜ cat mycase.scala badkext.scala
case class K(k: Int)
class SpecialK extends K(27)
Enforcement looks like
➜ scalac -Werror -feature -source future -d /tmp mycase.scala badkext.scala
-- Error: badkext.scala:2:23 --------------------------------------------------------------------------------------------------------------------
2 |class SpecialK extends K(27)
| ^^^^^
| Unless class K is declared 'open', its extension in a separate file should be enabled
| by adding the import clause 'import scala.language.adhocExtensions'
| or by setting the compiler option -language:adhocExtensions.
| See the Scala docs for value scala.language.adhocExtensions for a discussion
| why the feature should be explicitly enabled.
1 error found
The new support for such extensions looks like
➜ cat mycase.scala
open case class K(k: Int)
or
➜ cat badkext.scala
import scala.language.adhocExtensions
class SpecialK extends K(27)
It’s worth adding that a FAQ for someone (possibly a learner or with shallow knowledge of the language) who just wants to use a feature might look different from an expert document that might represent a project’s code policies.