I am running JDK 21 on the server. Is it possible to tell the Scala compiler to target the generated bytecode for JDK 21?
Is this worth doing or even bothering with, or shall I just stick with the default? Is there a list of optimizations that are made for each JDK version in the compiler?
Yes, you can set the compiler flag
-release 21 to:
- Make the compiler generate Java 21 bytecode.
- Make the compiler link your code to the Java 21 stdlib.
Optimization-wise, I think this doesn’t buy you much, to be honest.
However, for applications, there is no known (at least to me) downside to setting the flag. And, in general, it is always a good idea to match your target system the best you can.
Nevertheless, note that the server that builds your app (CI) also needs to run Java 21. But, again, it is always a good idea to match your target system the best you can.
The only explicit optimization I know of is to use modern string concatenation.
The classfile version also influences verification, if that is a feature.
As a reminder (to myself), compiling without the flag gives you a classfile version 52 (meaning JDK 8) but compiled against whatever your platform is (such as JDK 21). (That is for historical reasons? For Scala 2.12, it is a technical restriction.)
So without the flag, you should only run on the same version of the JDK.
I’d recommend always using the
--release flag, where libraries specify their lowest supported version (and guarantee they’re not using newer API) and apps specify their expected target platform (or, similarly, the lowest version that is deployed).
There ought to be a doc page with this info, but perhaps there is not. Even the doc page for the compiler option is quite out of date.
I am missing a documentation page with all the recommended flags (best practices) to speficy when starting a new project. Can someone say something about that?
It was only luck that I happened to discover the -release option.
That page is also missing, but most people turn to sbt-tpolecat.