Sunday, September 12, 2021

Managing multiple versions of Java locally: SDKMAN to the rescue!

I wanted to try the newly added Records to Java 16, mostly because I immediately had the feeling that they would be pretty much the same as Kotlin data classes. As it turns out, they are pretty similar but have certain differences, but that is not the point of this entry.

As I work on projects that still depend on Java 8, I couldn't just simply upgrade my version of Java. Luckily I have been using SDKMAN on my machine, even though I initially did not have a reason to do so, but as it happens, the new setup for my tests was rather straight forward.

Adding a new version of Java is just a matter of running the following command (in my case to add Java 16):

sdk install java 16.0.1.hs-adpt

And to use it you can:

sdk use java 16.0.1.hs-adpt

But it is a bit of a pain to have to run the 'use' command every time you want to work on that project. The solution is to add a config file in the root folder of your project called `.sdkmanrc`. This is the content of my config file:

>cat .sdkmanrc
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=16.0.1.hs-adpt

Finally, if you want the version in the rc file to run automatically when you cd into a particular project you can set this up in the overal sdkman config file, which on mac is at  `~/.sdkman/etc/config`. There you can change the default `false` value of the following property to true:

sdkman_auto_env=true

You can do a lot more with SDKMAN, but this was exactly what I needed for the particular tests I had in mind. Enjoy!