Introduction to Scala

This is meant to be a simple overview of Scala. We will not go deep into many concepts.In case you want to go deeper, check out the Scala Book

Scala is a modern programming language that supports object-oriented and functional programming. It runs on the JVM. It is a statically-typed language designed to address the criticisms of Java.

Features

  • It is a high level programming language.
  • It supports a fusion of functional and object-oriented programming.
  • It is statically typed.
  • It runs seamlessly with Java.
  • It can be run on the browser by integrating with JavaScript.
  • It has a concise and readable syntax.

Hello World

Create a file named hello.scala and add the following content to it.

 object HelloWorld {   def main(args: Array[String]) = {     println("Hello, World!");   } }
 @main def HelloWorld() = println("Hello, World!");

The above program can be compiled using the following command from a terminal assuming you have already installed Scala.

$ scalac hello.scala

You will now see a lot of files in the working directory. This indicates that the program has been compiled. The compiled program can be run using the following command:

$ scala HelloWorld

The HelloWorld can be replaced with whatever you named your main object (Scala 2) or main function (Scala 3) as.

Ta-dah! You have run your (probably) first Scala program.

Scala programs generally follow the structure used above, depending on the version of Scala you use.

The REPL

Like many modern programming language runtimes, Scala provides a REPL (Read-Evaluate-Print-Loop) via the command line that can be accessed through the scala command.

$ scalaWelcome to Scala 2.13.8 (OpenJDK 64-Bit Server VM, Java 17.0.4.1).Type in expressions for evaluation. Or try :help.scala> _ 

You can evaluate simple expressions via the REPL.

$ scalaWelcome to Scala 2.13.8 (OpenJDK 64-Bit Server VM, Java 17.0.4.1).Type in expressions for evaluation. Or try :help.scala> println("Hello World");Hello Worldscala> _