I have an sbt project with both Scala (2.13.1) and Java files.
I'd like to compile the java files using Java 14, including the preview features.
How can I do that?
Following oracle's docs above, I tried to set the javaOptions + javacOptions:
javaOptions ++= Seq("--enable-preview"), // when running
javacOptions ++= Seq("--enable-preview", "--release", "14"), // when compiling
but when I compile a simple Java file that uses the preview features like:
package example;
public record Person(String name, Integer age) {}
I get:
[error] /Users/dvir/learn/playground/src/main/java/example/Person.java:3:15: illegal start of type declaration
[error] public record Person(String name, Integer age) {}
[error] ^
Notes:
I work on Mac with AdoptOpenJDK 14.
My JAVA_HOME is /Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home .
When using jshell I can use preview features without any problems:
dvir@Mac ~/learn/playground$ jshell --enable-preview
| Welcome to JShell -- Version 14.0.2
| For an introduction type: /help intro
jshell> public record Person(String name, Integer age) {}
| created record Person
jshell> var alice = new Person("alice", 20)
alice ==> Person[name=alice, age=20]
jshell>
When I comment out the Person record (thus using only standard features from java 14, e.g switch expressions) but keep the javaOptions and javacOptions, I still get this warning:
[warn] Error reading API from class file: example.MainJava : java.lang.UnsupportedClassVersionError: Preview features are not enabled for example/MainJava (class file version 58.65535). Try running with '--enable-preview'
When I also comment out the javaOptions and javacOptions, the java code compile and runs as expected.
Notice that the compiler warning above is like the warning in this blog under the title Forced To ––enable–preview At Run Time.
Both the warning and the blog suggest to add ––enable–preview, as I did.
How do I setup sbt to work with java 14 preview features?