How to set Java version for SBT

Viewed 1872

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.

3 Answers

I think I have faced a similar issue. It happened because you did not set the Java_Home part. If you are using a mac, you have to set Java_Home path in .bashrc or .zshrc file which one you are using. I think it should work.

enter image description here

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.

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.

Related