Scala 3 extension method for object and Java class

In Scala 3 we can currently add an extension method for scala’s object on objectType.type, but seems that can’t be done for the Java class’ static member. Which can be invoked with <JavaClassName>.extensionMethodName(...)

There is a proposal in Kotlin Kotlin statics and static extensions by elizarov · Pull Request #347 · Kotlin/KEEP · GitHub

I didn’t look at the Kotlin solution, but how about something like this:

@main def entryPoint =
	type BigInteger = java.math.BigInteger
	object BigInteger { export java.math.BigInteger.* }
	extension ($: BigInteger.type)
		def RANDOM = new BigInteger("4") // chosen by fair dice roll

Would this be a acceptable workaround? I’ve added as demonstration a “RANDOM” “static” member on a custom object, which would appear in this scope like the synthetic companion object Scala would usually add for the Java type.

It’s not exactly what you ask for, it’s a simulation, but the resulting “look & feel” is almost the same as the wanted feature. It’s only two additional lines. Wouldn’t this be viable?

But maybe some experts have a better idea, though!

I think this could fairly easily be made to work once you have erased definitions. The problem is that String is not a real companion object so it cannot be passed around as a value, but you can define an extension method like this:

extension (erased a: String.type) def hello = "I am String"

Now you should be able to call String.hello since the “value” String is erased at runtime. Unfortunately in the latest snapshot release you get the error value hello is not a member of object String.

Could even be made more ergonomic if the compiler would define all java “companion objects” as instances of erased classes. Then you as a user don’t need to think about adding erased or not.

The ticket of record on this is add @static support for extension method · Issue #168 · lampepfl/dotty-feature-requests · GitHub

@Jasper-M I suggest you add your idea there, as it doesn’t seem to have been brought up before.