Introduction to Scala and Environment Setup
Overview
Welcome to the Scala tutorial series! In this first unit, we’ll help you get set up with everything you need to start programming in Scala. We’ll cover:
Installing Scala
Prerequisites
Before installing Scala, ensure you have Java Development Kit (JDK) installed on your machine. Scala runs on the Java Virtual Machine (JVM), and having the JDK is essential.
Verify Java Installation
java -version
If Java is not installed, download and install it from the Oracle website or use your package manager.
Install Scala
Scala can be installed via several methods. Here, we’ll use Scala Build Tool (sbt), which also sets up a build environment that can be handy later.
Using SDKMAN
SDKMAN is a tool for managing parallel versions of multiple Software Development Kits on most Unix-based systems. Here’s how to install Scala using SDKMAN:
Install SDKMAN:
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
Install Scala:
sdk install scala
Verify installation:
scala -version
Alternative: Direct Download
You can also download Scala directly from the official Scala website.
Setting Up an IDE
An Integrated Development Environment (IDE) enhances productivity with features like syntax highlighting, project management, and debugging.
IntelliJ IDEA
Download and install IntelliJ IDEA from the JetBrains website.
Open IntelliJ IDEA and select New Project
.
Choose Scala
from the list of project types. If the Scala plugin is not installed, IntelliJ will prompt you to install it.
Configure the SDK. Ensure you select your JDK installation.
Complete the project setup. IntelliJ will create a new Scala project for you.
Visual Studio Code
Download and install Visual Studio Code from the official website.
Open Visual Studio Code and go to the Extensions view by clicking on the Extensions icon in the Sidebar.
Search for the Metals
extension (Scala language server) and install it.
Create a new Scala project by opening your terminal in VS Code and running:
sbt new scala/hello-world.g8
Using the Scala REPL
The Scala REPL (Read-Eval-Print Loop) allows you to interactively run Scala code snippets, making it a great tool for learning and prototyping.
Starting the Scala REPL
Once Scala is installed, you can start the REPL by simply typing:
scala
Example Usage
Here are some basic commands to get you started:
Define a variable:
val x = 10
Define a function:
def add(a: Int, b: Int): Int = a + b
Call the function:
add(5, 7)
Exit the REPL by typing :quit
or pressing Ctrl+D
.
Now that your environment is set up, you’re ready to start coding in Scala! Continue to the next unit for more in-depth programming tutorials and advanced topics.
Installing Scala and Necessary Tools
In this section, we will cover the installation of Scala and the tools required to start developing in Scala, set up an Integrated Development Environment (IDE), and use the Scala REPL (Read-Eval-Print Loop).
1. Installing Scala
To install Scala, you can use multiple methods. Here we will use “Scala installer” for simplicity.
Step 1: Install SDKMAN!
SDKMAN! is a tool for managing parallel versions of multiple Software Development Kits on most Unix-based systems.
# Install SDKMAN!
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
Step 2: Install Scala
Once SDKMAN! is set up, you can install Scala by executing:
# Install the latest stable version of Scala
sdk install scala
Step 3: Verify Installation
Verify that Scala is installed successfully by checking its version:
scala -version
You should see output indicating the installed version of Scala.
2. Setting Up the IDE – IntelliJ IDEA
Step 1: Download and Install IntelliJ IDEA
Follow the Official JetBrains website to download and install Intellij IDEA.
Step 2: Install Scala Plugin
Once IntelliJ IDEA is installed, open it and perform the following to install the Scala plugin:
File
> Settings
.Plugins
from the menu.Scala
and click Install
.Step 3: Create a New Scala Project
Create New Project
.Next
.Finish
to create the project.3. Using the Scala REPL
Step 1: Launch the Scala REPL
Open your terminal and type:
scala
This command will start the Scala REPL, where you can execute Scala code interactively.
Step 2: Running Scala Code in REPL
Once in the Scala REPL, you can type Scala code to see immediate results. For example:
scala> println("Hello, Scala!")
You should see the output:
Hello, Scala!
Step 3: Exit the REPL
To exit the Scala REPL, simply type:
:quit
or press Ctrl+D
.
Conclusion
You have successfully installed Scala, set up IntelliJ IDEA as your IDE, and learned to use the Scala REPL. With these tools in hand, you are ready to start your Scala development.
Setting Up IntelliJ IDEA for Scala Development
Step 1: Install IntelliJ IDEA
If IntelliJ IDEA is not already installed on your machine, download and install the Community or Ultimate edition from the official website.
Step 2: Install the Scala Plugin
File
-> Settings
(Windows/Linux) or IntelliJ IDEA
-> Preferences
(macOS).Settings
or Preferences
window, go to Plugins
on the left panel.Install
button next to the Scala plugin.Step 3: Create a New Scala Project
Create New Project
.New Project
window, select Scala
on the left panel.sbt
(Scala Build Tool) in the right panel.Next
.Step 4: Configure Project Details
sbt
version and Scala
version you wish to use.Finish
.Step 5: Verify Your Scala Setup
Once the project opens, wait for sbt to resolve dependencies and set up the project completely.
Create a new Scala object:
src/main/scala
in the Project Explorer.New
-> Scala Class
.Object
and provide a name for your object, e.g., HelloWorld
.Implement a simple Scala program:
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, World!")
}
}
Run the Scala Object:
HelloWorld
object.Run 'HelloWorld'
.Step 6: Using Scala REPL in IntelliJ IDEA
View
-> Tool Windows
-> Terminal
).scala
and hitting Enter.scala
Now you can execute Scala commands directly. For example:
scala> println("Hello, Scala REPL!")
Conclusion
You have now set up IntelliJ IDEA for Scala development, created a simple Scala project, and verified it by running a basic Scala object. Additionally, you have accessed and used the Scala REPL within the IDE to execute Scala commands interactively.
Configuring Visual Studio Code for Scala
This section guides you on how to configure Visual Studio Code for Scala development. It covers installing necessary extensions, configuring your project, and verifying the setup.
Step 1: Install Necessary Extensions
Ctrl+Shift+X
.Step 2: Create a New Scala Project
Ctrl+Shift+P
to open the Command Palette.Metals: New Scala Project
and select it.Step 3: Configure Build Tool (sbt)
sbt
build file named build.sbt
at the root of your project:
name := "my-scala-project"
version := "0.1.0"
scalaVersion := "2.13.6"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.9" % Test
Step 4: Verify Configuration
Ensure the Metals Server is Running:
Compile the Project:
sbt compile
Run the Scala REPL:
Ctrl+Shift+P
).Metals: Run Worksheet
and select it.example.sc
):
println("Hello, Scala!")
Run Main Application:
src/main/scala
:
object Main extends App {
println("Hello, World!")
}
F5
or by running:
sbt run
This setup allows you to develop, compile, and run Scala applications using Visual Studio Code. Ensure your project configurations and build tool settings are correctly set up for effective development.
Exploring the Scala REPL
The Scala REPL (Read-Eval-Print Loop) is an interactive shell that allows you to write and execute Scala code in real-time. It’s a powerful tool for experimenting with code, testing functions, and understanding how Scala works. In this part, we will explore how to effectively use the Scala REPL.
Starting the Scala REPL
Once you have Scala installed, you can start the REPL by opening a terminal and executing:
scala
You should see the REPL prompt, which is typically represented by an arrow (scala>
):
Welcome to Scala 2.13.3 (OpenJDK 64-Bit Server VM, Java 11.0.2).
Type in expressions for evaluation. Or try :help.
scala>
Basic Commands
You can type Scala expressions directly into the REPL and see the results immediately. Here are some basic examples:
scala> 1 + 1
res0: Int = 2
scala> val x = 10
x: Int = 10
scala> x * 2
res1: Int = 20
In the above example:
res0
and res1
are automatically named result variables.val x = 10
defines a new immutable variable x
.Defining Functions
You can define functions in the REPL to reuse code snippets:
scala> def add(a: Int, b: Int): Int = a + b
add: (a: Int, b: Int)Int
scala> add(3, 4)
res2: Int = 7
Working with Collections
Scala collections can also be used directly within the REPL:
scala> val numbers = List(1, 2, 3, 4, 5)
numbers: List[Int] = List(1, 2, 3, 4, 5)
scala> numbers.map(_ * 2)
res3: List[Int] = List(2, 4, 6, 8, 10)
Exploring Object-Oriented Features
You can define classes and objects to see OOP principles in action:
scala> class Person(val name: String, val age: Int)
defined class Person
scala> val alice = new Person("Alice", 25)
alice: Person = Person@1b6d3586
scala> alice.name
res4: String = Alice
scala> alice.age
res5: Int = 25
Using :help Command
You can use the :help
command to see a list of special commands available in the REPL:
scala> :help
All commands can be abbreviated, e.g., :he instead of :help.
:load <path> load and interpret a Scala file
:quit exit the interpreter
:reset reset the interpreter, forgetting all session entries
:sh <command line> run a shell command (result is implicitly => List[String])
:help [<command>] print the usage message for or describe <command>
Exiting the Scala REPL
To exit the REPL, you can use the :quit
command:
scala> :quit
Or you can use the shortcut Ctrl + D
(may vary depending on the terminal).
Conclusion
The Scala REPL is an essential tool for anyone learning Scala. It provides a quick feedback loop, making it perfect for experimenting with Scala syntax, testing functions and classes, and getting familiar with Scala’s features. By mastering the REPL, you can significantly speed up your Scala learning process.
Creating and Running Your First Scala Program
Now that you’ve set up your Scala environment and IDE, it’s time to create and run your first Scala program. We will walk you through writing a simple “Hello, World!” application in Scala.
Step 1: Create a New Scala Project
Open Your IDE: Open IntelliJ IDEA or Visual Studio Code where you have previously configured the Scala plugin.
Create a New Project:
File > New > Project
.Scala
from the project types, then proceed.- Visual Studio Code:
Create a new folder for your project, then open this folder in VS Code.
Step 2: Create a Scala Object
Create a New Scala File:
src
(if it doesn’t already exist).src
, create a directory named main
, and inside main
, create another directory named scala
.-
Create a Scala File:
Insidesrc/main/scala
, create a new file namedHelloWorld.scala
.
Write Your Scala Code:
HelloWorld.scala
and add the following code:object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, World!")
}
}
Step 3: Compile and Run Your Scala Program
-
Compile the Program:
- Using IntelliJ IDEA:
- Right-click on
HelloWorld.scala
in the project explorer and selectRun 'HelloWorld'
.
- Right-click on
- Using Visual Studio Code:
- Open the terminal (Ctrl + `) and navigate to your project directory.
- Run the following command to compile the program:
scalac src/main/scala/HelloWorld.scala
- Using IntelliJ IDEA:
-
Run the Compiled Code:
-
IntelliJ IDEA:
- The IDE should automatically compile and run the program, showing “Hello, World!” in the console output.
-
Visual Studio Code:
- Run the following command in the terminal:
scala HelloWorld
- You should see the output:
Hello, World!
-
Congratulations! You have successfully created and run your first Scala program.
Best Practices for a Productive Scala Development Environment
Structuring Your Project
A well-structured project is crucial for maintaining code readability and manageability. In Scala, the typical structure follows the SBT (Simple Build Tool) convention:
my-scala-project/
|-- build.sbt
|-- project/
|-- src/
|-- main/
| |-- scala/
| | |-- com/
| | |-- example/
| | |-- Main.scala
|-- test/
|-- scala/
|-- com/
|-- example/
|-- MainSpec.scala
build.sbt Example
The build.sbt
file defines your project’s settings and dependencies. Here is a basic example:
name := "MyScalaProject"
version := "0.1"
scalaVersion := "2.13.6"
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "3.2.9" % Test
)
Code Formatting
Using a consistent code style is essential for collaborative programming. scalafmt
is a popular tool for automatically formatting Scala code.
Install scalafmt
by adding it to your project/plugins.sbt
:
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6")
Configure scalafmt
by creating a .scalafmt.conf
file in the root of your project:
version = 2.4.6
maxColumn = 100
docstrings = ScalaDoc
includeCurlyBraceInSelectChains = false
align.preset = most
Run scalafmt
via SBT:
sbt scalafmt
Using Linting Tools
Static code analysis tools help you find potential issues before they become bugs. Scalastyle
and Scapegoat
are two popular linting tools.
Add Scalastyle
to your project/plugins.sbt
:
addSbtPlugin("org.scalastyle" % "scalastyle-sbt-plugin" % "1.0.0")
Add Scapegoat
to your build.sbt
:
addSbtPlugin("com.sksamuel.scapegoat" % "sbt-scapegoat" % "1.3.11")
scapegoatVersion in ThisBuild := "1.3.11"
Running Linting Tools
Run Scalastyle using SBT:
sbt scalastyle
Run Scapegoat using SBT:
sbt scapegoat
Unit Testing
Testing is a fundamental part of any productive development environment. ScalaTest is the most commonly used testing library.
Here’s an example of a unit test using ScalaTest:
// src/test/scala/com/example/MainSpec.scala
import org.scalatest.flatspec.AnyFlatSpec
class MainSpec extends AnyFlatSpec {
"The Main object" should "say hello" in {
assert(Main.hello() == "Hello, world!")
}
}
Continuous Integration
Automate your build and testing process using a CI service like GitHub Actions. Create a .github/workflows/scala.yml
file:
name: Scala CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@v2
with:
java-version: '11'
- name: Cache SBT
uses: actions/cache@v2
with:
path: |
~/.ivy2/cache
~/.sbt
key: ${{ runner.os }}-sbt-${{ hashFiles('**/build.sbt') }}
restore-keys: |
${{ runner.os }}-sbt
- name: sbt test
run: sbt test
Conclusion
By following these best practices, you will ensure a productive and maintainable Scala development environment. These practices will help your team write clean, well-structured code, and catch issues early in the development lifecycle.