LondonMassive
LondonMassive

Reputation: 447

How to set Java version for SBT

I am trying to run a scala program, in which there are errors with Java 16. My colleague is using Java 15, and all is fine. When i type java -version in my terminal it says i am using Java 15. However, when i run sbt run -v, it says it is using Java 16, and thus the program throws errors.

I am seeing people talk about this sbt-extra thing, but not a whole lot of explanation on how to use it. I do not even have Java 16 installed on my Mac, so I am really confused as to why SBT says this.

Upvotes: 8

Views: 15924

Answers (4)

samthebest
samthebest

Reputation: 31515

The best way is to do this via the build.sbt file so then it's specific to just that project not your entire local environment. I.e. add the following to build.sbt:

  javacOptions ++= Seq("-source", "11", "-target", "11")

Upvotes: 6

Vimit Dhawan
Vimit Dhawan

Reputation: 677

Add this to ~/.bash_profile, ~/.bashrc or ~/.zshrc (depending on shell preferences/OS), or just run this before running sbt in a terminal:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home

It's better though to do this per-sbt project via build.sbt as per this answer: https://stackoverflow.com/a/76456295/1586965

Upvotes: 6

donlja
donlja

Reputation: 11

Another option which worked for me is to add the version of java you want to be used to the front of your terminal PATH environment variable. Since I used homebrew to install openjdk, I used the path they suggested resulting in the following path to use openjdk version 11.

export PATH="usr/local/opt/openjdk@11/bin:$PATH"

Note - the openjdk path I used I think is just the homebrew symlink to the actual java installation which is in /Library/Java/JavaVirtualMachines. You could probably just use that actual path but I didn't test it.

Upvotes: 1

Emiliano Martinez
Emiliano Martinez

Reputation: 4123

To handle your installed jvms you can use Jenv.

To install jenv:

git clone https://github.com/jenv/jenv.git ~/.jenv
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile

echo 'eval "$(jenv init -)"' >> ~/.bash_profile

Then, you can add your intalled jvms. In Mac, if you have installed them via brew you can find those in: /Library/Java/JavaVirtualMachines.

Then add them to jenv:

jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home 
jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home 

You can see the available jvms in jenv:

jenv_versions

you can set the default jvm with the command:

jenv global 1.8.0.121

Then, execute sbt in some of your projects and you should see that jvm as the jvm that sbt is using.

Upvotes: 2

Related Questions