How To Install Scala on Rocky Linux 9
In this tutorial, we will show you how to install Scala on Rocky Linux 9. Scala, a powerful programming language that combines object-oriented and functional programming paradigms, has become increasingly popular among developers building scalable applications. Whether you’re developing data-intensive systems, distributed applications, or simply exploring functional programming, having Scala properly installed on your Rocky Linux 9 environment is essential. This comprehensive guide walks you through various installation methods, configuration steps, and troubleshooting techniques to ensure a smooth Scala development experience on Rocky Linux 9.
Understanding Scala and Its Requirements
What is Scala?
Scala (Scalable Language) is a high-level, statically-typed programming language that seamlessly integrates features of object-oriented and functional programming. It runs on the Java Virtual Machine (JVM), allowing you to leverage existing Java libraries while providing more expressive syntax and powerful abstractions. Scala’s design emphasizes code conciseness, type safety, and scalability-making it ideal for everything from small scripts to large enterprise applications.
Why Use Scala on Rocky Linux?
Rocky Linux 9, a production-ready enterprise operating system designed as a downstream build of Red Hat Enterprise Linux (RHEL), provides a stable foundation for running Scala applications. The combination offers several advantages:
- Enterprise-grade stability and security
- Long-term support cycles
- Excellent performance characteristics for server environments
- Compatibility with a wide range of hardware
- Strong community support
System Requirements
Before installing Scala on Rocky Linux 9, ensure your system meets these requirements:
- A Rocky Linux 9 installation with administrative access
- Minimum 2GB RAM (4GB+ recommended for development)
- At least 10GB free disk space
- Internet connection for downloading packages
- JVM (Java Virtual Machine) – OpenJDK 11 or 17 is recommended for Scala 3
Installation Methods Overview
This guide covers multiple installation approaches:
- Coursier Method (Recommended): Using the official Scala installer tool
- Repository Installation: Installing directly via DNF package manager
- Manual Installation: Downloading and configuring Scala manually
Each method has its advantages, with Coursier being the official recommendation for most users due to its simplicity and completeness.
Preparing Your Rocky Linux 9 System
Updating Your System
Always start with an updated system. Open your terminal and execute:
sudo dnf makecache
This command updates the package metadata cache. You should see output similar to:
Rocky Linux 9 - BaseOS 1.3 kB/s | 4.1 kB 00:03
Rocky Linux 9 - AppStream 1.2 kB/s | 4.5 kB 00:03
Rocky Linux 9 - Extras 974 B/s | 2.9 kB 00:03
Metadata cache created.
Next, update all installed packages to their latest versions:
sudo dnf update -y
If this command updates kernel-related packages, reboot your system before proceeding:
sudo reboot
After rebooting, verify your Rocky Linux version:
cat /etc/rocky-release
Output should show something similar to:
Rocky Linux release 9.1 (Blue Onyx)
Installing Required Dependencies
Scala requires Java and several supporting tools. Install them with:
sudo dnf install -y wget gzip java-17-openjdk
This command installs:
- wget: For downloading files
- gzip: For handling compressed files
- java-17-openjdk: The OpenJDK Java runtime environment
Verifying Java Installation
Confirm Java is properly installed by checking its version:
java --version
You should see output similar to:
openjdk 17.0.6 2023-01-17 LTS
OpenJDK Runtime Environment (Red_Hat-17.0.6.0.10-3.el9_1) (build 17.0.6+10-LTS)
OpenJDK 64-Bit Server VM (Red_Hat-17.0.6.0.10-3.el9_1) (build 17.0.6+10-LTS, mixed mode, sharing)
The exact version may differ, but ensure it’s Java 11 or newer, as Scala 3 requires at least Java 11.
Method 1: Installing Scala Using Coursier (Recommended)
The official recommended approach for installing Scala is using Coursier, a dependency management tool for the JVM that provides a convenient installer for Scala and related tools.
What is Coursier?
Coursier (cs
) is a dependency resolver that simplifies the installation and management of Scala and its ecosystem tools. It automatically handles Java version compatibility, path configurations, and installs complementary development tools.
Downloading the Coursier Installer
Download the Coursier launcher using wget:
wget -O cs-x86_64-pc-linux.gz https://github.com/coursier/coursier/releases/latest/download/cs-x86_64-pc-linux.gz
Extract the downloaded file:
gzip -d cs-x86_64-pc-linux.gz
Rename the extracted file and make it executable:
mv cs-x86_64-pc-linux cs
chmod +x cs
Executing the Coursier Setup
Run the Coursier setup script:
./cs setup
During execution, Coursier will:
- Check if a compatible JVM is installed
- Ask to add its bin directory to your PATH (recommended to answer ‘Y’)
- Install standard Scala applications and tools
The output will look similar to:
Checking if a JVM is installed
Found a JVM installed under /usr/lib/jvm/java-17-openjdk-17.0.6.0.10-3.el9_1.x86_64.
Checking if ~/.local/share/coursier/bin is in PATH
Should we add ~/.local/share/coursier/bin to your PATH via ~/.profile, ~/.bash_profile? [Y/n] Y
Checking if the standard Scala applications are installed
Installed ammonite
Installed cs
Installed coursier
Installed scala
Installed scalac
Installed scala-cli
Installed sbt
Installed sbtn
Installed scalafmt
Environment Configuration
Apply the new environment settings to your current session:
source ~/.bash_profile
Installation Verification
Verify your Scala installation by checking its version:
scala -version
You should see output similar to:
Scala code runner version 3.2.2 -- Copyright 2002-2024, LAMP/EPFL
The exact version may vary depending on when you’re installing, but it should indicate a Scala 3.x version.
Method 2: Installing Scala from Repositories
While the Coursier method is recommended, you can alternatively install Scala directly through package repositories. This approach may be simpler but provides less flexibility.
Repository Configuration
Unfortunately, Scala packages aren’t available in the default Rocky Linux repositories. You would need to configure EPEL (Extra Packages for Enterprise Linux) repository first:
sudo dnf install -y epel-release
sudo dnf makecache
Package Installation
After configuring the repository, install Scala:
sudo dnf install -y scala
Note that this method typically provides an older version of Scala (likely Scala 2.x) compared to the Coursier method which installs the latest Scala 3.
Manual Configuration Steps
You may need to manually configure environment variables. Create a file for Scala environment settings:
sudo tee /etc/profile.d/scala.sh << 'EOF'
export SCALA_HOME=/usr/share/scala
export PATH=$PATH:$SCALA_HOME/bin
EOF
Make the script executable and apply changes:
sudo chmod +x /etc/profile.d/scala.sh
source /etc/profile.d/scala.sh
Comparing with Coursier Method
The repository installation method has some trade-offs compared to Coursier:
Advantages:
- Simpler installation process
- Package management handled by DNF
- Easier system-wide installation
Disadvantages:
- Typically older Scala versions
- Limited tooling (missing tools like sbt, ammonite)
- Less control over Java version integration
- Fewer automatic configuration settings
Testing Your Scala Installation
Accessing the Scala REPL
Scala provides an interactive shell called the REPL (Read-Evaluate-Print Loop) for quick testing and experimentation. Start it by typing:
scala
You should see a welcome message followed by a prompt:
Welcome to Scala 3.2.2 (17.0.6, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala>
Simple Expressions in REPL
Test the REPL by entering a few expressions:
scala> 1 + 1
val res0: Int = 2
scala> println("Hello, Rocky Linux!")
Hello, Rocky Linux!
scala> val numbers = List(1, 2, 3, 4, 5)
val numbers: List[Int] = List(1, 2, 3, 4, 5)
scala> numbers.map(_ * 2).filter(_ > 5)
val res1: List[Int] = List(6, 8, 10)
Exit the REPL using :quit
or pressing Ctrl+D.
Creating Your First Scala Program
Let’s create a simple “Hello World” program. First, create a file named HelloWorld.scala
:
vim HelloWorld.scala
Add the following code:
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, Rocky Linux 9!")
}
}
Compiling and Running Scala Code
Compile your program using the Scala compiler:
scalac HelloWorld.scala
This generates bytecode files. Run your program with:
scala HelloWorld
You should see the output:
Hello, Rocky Linux 9!
Advanced Configuration
Setting Up Environment Variables
For more control over your Scala environment, consider setting these variables:
# Add to your ~/.bashrc file
export SCALA_HOME=~/.local/share/coursier
export PATH=$PATH:$SCALA_HOME/bin
export JAVA_OPTS="-Xms512M -Xmx2G -Xss2M"
Reload your bash configuration:
source ~/.bashrc
Configuring Multiple Scala Versions
Coursier allows managing multiple Scala versions. Install a specific version:
cs install scala:2.13.16
Run a specific version when needed:
cs launch scala:2.13.16 --main scala.tools.nsc.MainGenericRunner
Integration with Build Tools
Most Scala projects use SBT (Scala Build Tool) for dependency management and build automation. Verify SBT is installed:
sbt --version
Create an SBT configuration in your home directory:
mkdir -p ~/.sbt/1.0
echo 'SBT_OPTS="-Xms512M -Xmx2G -Xss2M"' > ~/.sbt/1.0/sbt.ini
Creating a Complete Scala Project
Project Directory Structure
A typical Scala project structure includes:
myproject/
├── build.sbt
├── project/
│ └── build.properties
├── src/
│ ├── main/
│ │ └── scala/
│ │ └── com/
│ │ └── example/
│ │ └── Main.scala
│ └── test/
│ └── scala/
│ └── com/
│ └── example/
│ └── MainTest.scala
└── README.md
Let’s create a simple project:
mkdir -p myproject/src/main/scala/com/example
cd myproject
Building a Sample Application
Create a build configuration file:
cat > build.sbt << EOF
name := "MyRockyLinuxProject"
version := "0.1"
scalaVersion := "3.2.2"
libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "2.1.1"
EOF
Create a project properties file:
mkdir -p project
echo "sbt.version=1.8.0" > project/build.properties
Create a sample application file:
mkdir -p src/main/scala/com/example
cat > src/main/scala/com/example/Main.scala << EOF package com.example object Main { def main(args: Array[String]): Unit = { println("Starting application...") val numbers = (1 to 10).toList val doubled = numbers.map(_ * 2) val filtered = doubled.filter(_ > 10)
println(s"Original numbers: \${numbers}")
println(s"Doubled: \${doubled}")
println(s"Filtered (> 10): \${filtered}")
println("Application completed.")
}
}
EOF
Using External Libraries
The build.sbt file already includes the scala-parser-combinators library. Let’s modify our application to use it:
cat > src/main/scala/com/example/ParserExample.scala << EOF package com.example import scala.util.parsing.combinator._ class SimpleParser extends RegexParsers { def word: Parser[String] = """[a-z]+""".r def number: Parser[Int] = """[0-9]+""".r ^^ { _.toInt } def phrase: Parser[List[Either[String, Int]]] = rep(word ^^ { Left(_) } | number ^^ { Right(_) }) } object ParserExample { def main(args: Array[String]): Unit = { val parser = new SimpleParser val input = "hello 42 world 99" parser.parse(parser.phrase, input) match { case parser.Success(result, _) =>
println("Parsing successful!")
result.foreach {
case Left(word) => println(s"Word: \${word}")
case Right(number) => println(s"Number: \${number}")
}
case failure: parser.NoSuccess =>
println(s"Parsing failed: \${failure.msg}")
}
}
}
EOF
Testing and Execution
Compile and run your project using SBT:
# Compile the project
sbt compile
# Run the Main application
sbt "runMain com.example.Main"
# Run the ParserExample application
sbt "runMain com.example.ParserExample"
Performance Optimization
JVM Tuning for Scala
Optimize JVM settings for better Scala performance:
export JAVA_OPTS="-Xms1G -Xmx4G -XX:+UseG1GC -XX:MaxGCPauseMillis=200"
For production servers, consider these additional settings:
export JAVA_OPTS="$JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/scala/heapdump.hprof"
Compiler Options
Add these compiler options to your build.sbt
for better performance:
scalacOptions ++= Seq(
"-opt:l:inline",
"-opt-inline-from:**",
"-Yopt-inline-heuristics:at-inline-annotated"
)
Monitoring Scala Applications
Install basic monitoring tools:
sudo dnf install -y htop iotop
For JVM-specific monitoring, use VisualVM (requires GUI access) or JMX with tools like jconsole.
Troubleshooting Common Issues
Path and Environment Problems
If scala
command is not found after installation:
# Check if Scala is in PATH
echo $PATH | grep scala
# If missing, add Coursier bin directory to PATH
echo 'export PATH=$PATH:~/.local/share/coursier/bin' >> ~/.bashrc
source ~/.bashrc
Java Version Conflicts
If you encounter Java version compatibility issues:
# Check current Java version
java -version
# Install a compatible Java version if needed
sudo dnf install -y java-11-openjdk-devel
# Configure alternatives to select the right version
sudo alternatives --config java
Compiler Errors
For “symbol not found” errors:
# Clean and recompile the project
sbt clean compile
For “OutOfMemoryError” during compilation:
# Increase memory allocation
export SBT_OPTS="-Xmx4G -XX:+UseG1GC"
sbt compile
Installation Failures
If Coursier installation fails:
# Remove partial installation
rm -rf ~/.local/share/coursier
# Try manual installation
wget -O scala.tgz https://downloads.lightbend.com/scala/2.13.16/scala-2.13.16.tgz
tar -xzf scala.tgz
sudo mv scala-2.13.16 /usr/local/share/scala
echo 'export PATH=$PATH:/usr/local/share/scala/bin' >> ~/.bashrc
source ~/.bashrc
Uninstalling Scala
Using Coursier to Uninstall
If you installed Scala with Coursier, uninstall with:
cs uninstall scala
Confirm the uninstallation was successful:
Uninstalled scala
Manual Removal Steps
If you installed manually or need to completely remove all components:
# Remove Coursier directory
rm -rf ~/.local/share/coursier
# Remove Coursier PATH entry from profile files
sed -i '/coursier\/bin/d' ~/.bashrc ~/.bash_profile ~/.profile
# If installed via package manager
sudo dnf remove -y scala
Verifying Complete Removal
Confirm Scala is completely removed:
which scala
scala --version
Both commands should return nothing or “command not found” errors if the uninstallation was successful.
Congratulations! You have successfully installed Scala. Thanks for using this tutorial for installing the Scala programming language on your Rocky Linux 9 system. For additional or useful information, we recommend you check the official Scala website.