Blogumentation: Java language versions from SBT
Briefly

Blogumentation: Java language versions from SBT
"Problem: setting up a new Scala application (with SBT as build tool because I don't feel like learning Mill), and I don't want it to be stuck in out-of-date language features (or rather, stuck being unable to use modern language features because we accidentally used some incompatible feature or syntax and locked outselves in). In particular, I'm using a JRE version 21 (current long-term-support) base Docker image, and wanted to ensure that generated classfiles target that environment."
"The thing to know is that by default, SBT uses the JDK of whatever JRE is used to launch it. In my case, that's the stock openjdk-11 that I put on my Ubuntu machine lo these many years ago. Now, of course, Java commits to backwards compatibility, meaning that if we compile the application under Java 11 and package it into a JRE-21 base image, it should run fine. But that's not the same thing as writing for the current LTS Java."
"The next-most-common approach I came across was to use the -target command line flag to scalac by adjusting scalacOptions: ThisBuild / scalacOptions ++= Seq("-target:21") This used to be correct many versions of Scala ago, but since... well, at least since a few years, and I'm too lazy to pin down exactly when, scalac no longer accepts the target flag, resulting in the following message in SBT output: [info] compiling 1 Scala source to /path/to/repo/target/scala-3.3.6/classes ...[warn] bad option '-target:"
SBT uses the JDK of the JRE that launches it, so an older local JDK can cause compiled classfiles to target an older Java version even when deploying to Java 21. Adjusting javacOptions only affects Java source compilation and does not change Scala output. The historical scalac -target flag is no longer accepted by recent Scala compilers and yields a bad option warning. The correct way to control the generated classfile Java version from scalac is to set -java-output-version in scalacOptions (for example -java-output-version:21) so produced classfiles target the intended runtime.
Read at Medium
Unable to calculate read time
[
|
]