Reputation: 6206
I have a project which includes both java code and scala code.
The structure looks like:
--src
-- main
--java
myjavacode.java
--scala
myscalacode.scala
Now everytime when I run sbt package
, the scala code will be complied in Java 7, but java code will be complied in Java 8.
I think I have specified the JDK to 1.7, but I still can not change java code back to Java 7 version.
What should I do in Intellij or build.sbt file?
Upvotes: 0
Views: 1571
Reputation: 8279
SBT is pretty smart when it comes to Scala: you can specify which version of the Scala compiler and runtime libraries you want via the scalaVersion
property, and SBT will download that version and use it to compile your Scala sources.
You can also specify the version of Java bytecode that is emitted by the Scala compiler through specifying the -target
option in scalacOptions
property. For example,
scalacOptions += "-target:jvm-1.7"
However, when it comes to compiling Java sources, the currently selected JDK that you're using to run SBT is used. So if Java 8 is your default version of Java, and that's being used to run SBT, then that's the version used to compile your Java sources - and I don't believe that there's anything you can do about that in your SBT build file except to complain if the current Java version is the wrong one.
However, you can specify a minimum Java version, then use the -source
and -target
options of the Java compiler to limit syntax and output to the version you require.
For example, the following works with any version of Java after version 1.7, but only compiles files adhering to 1.7 syntax, and outputs 1.7 bytecode:
// We need at least Java 7.
initialize := {
val _ = initialize.value // Needed to run previous initialization.
assert(scala.util.Properties.isJavaAtLeast("1.7"), "My project requires Java 7 or later")
}
// Configure Java compiler appropriately.
javacOptions ++= Seq(
"-source", "1.7",
"-target", "1.7",
"-bootclasspath", "C:\\jdk1.7.0\\lib\\rt.jar"
)
Note that you still need access to a Java 1.7 runtime library (the location of which is specified by the -bootclasspath
argument).
If that doesn't do the trick, then you'll need to specify the version of Java you want by changing SBT's configuration. See this question for more details when running SBT from the command line. For SBT builds within IntelliJ, you'll need to specify the Project JDK to be used with SBT.
Upvotes: 3