Way back in the early days of Scala, one of the notable innovations vs Java was that Scala permits imports at any point in a program’s structure, rather than just top level.
I’ve recently noticed that there is one exception however, where imports do not seem to be permitted, and where it would be convenient to use them: at the top of a block of extension methods.
A key use case for extension methods is to add behavior to an existing class we didn’t define and that the creator didn’t provide.
When the added behavior requires significant code across multiple methods, it would be nice to be able to bring the members of the extended class into scope using a single import, as occurs when we are inside its class.
A toy example, but hopefully enough to convey the need. I would like to be able to write the isMinor
method as if it were defined on the Person class:
case class PrexistingPersonClass(name: String, age: Int)
extension (p: PrexistingPersonClass)
import p.*
def isMinor: Boolean = age < 18
As at Scala 3.4.0-RC1, this is not supported. We can place an import inside each method (ie within isMinor
) but when there are many such methods, it adds too much overhead. A single import at the top of the extension block would be preferable.
It’s slightly odd & inconsistent that import can be used in most places, but not here.