Scala Language

Getting started with Scala Language

Remarks#

Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages.

Most given examples require a working Scala installation. This is the Scala installation page, and this is the ‘How to setup Scala’ example. scalafiddle.net is a good resource for executing small code examples over the web.

Versions#

VersionRelease Date
2.10.12013-03-13
2.10.22013-06-06
2.10.32013-10-01
2.10.42014-03-24
2.10.52015-03-05
2.10.62015-09-18
2.11.02014-04-21
2.11.12014-05-21
2.11.22014-07-24
2.11.42014-10-30
2.11.52014-01-14
2.11.62015-03-05
2.11.72015-06-23
2.11.82016-03-08
2.11.112017-04-19
2.12.02016-11-03
2.12.12016-12-06
2.12.22017-04-19

Hello World by Defining a ‘main’ Method

Place this code in a file named HelloWorld.scala:

object Hello {
  def main(args: Array[String]): Unit = {
    println("Hello World!")
  }
}

Live demo

To compile it to bytecode that is executable by the JVM:

$ scalac HelloWorld.scala

To run it:

$ scala Hello

When the Scala runtime loads the program, it looks for an object named Hello with a main method. The main method is the program entry point and is executed.

Note that, unlike Java, Scala has no requirement of naming objects or classes after the file they’re in. Instead, the parameter Hello passed in the command scala Hello refers to the object to look for that contains the main method to be executed. It is perfectly possible to have multiple objects with main methods in the same .scala file.

The args array will contain the command-line arguments given to the program, if any. For instance, we can modify the program like this:

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello World!")
    for {
      arg <- args
    } println(s"Arg=$arg")
  }
}

Compile it:

$ scalac HelloWorld.scala

And then execute it:

$ scala HelloWorld 1 2 3
Hello World!
Arg=1
Arg=2
Arg=3

Hello World by extending App

object HelloWorld extends App {
  println("Hello, world!")
}

Live demo

By extending the App trait, you can avoid defining an explicit main method. The entire body of the HelloWorld object is treated as “the main method”.

Delayed Initialization

Per the official documentation, App makes use of a feature called Delayed Initialization. This means that the object fields are initialized after the main method is called.

Delayed Initialization

Per the official documentation, App makes use of a feature called Delayed Initialization. This means that the object fields are initialized after the main method is called.

DelayedInit is now deprecated for general use, but is still supported for App as a special case. Support will continue until a replacement feature is decided upon and implemented.

To access command-line arguments when extending App, use this.args:

object HelloWorld extends App {
  println("Hello World!")
  for {
    arg <- this.args
  } println(s"Arg=$arg")
}

When using App, the body of the object will be executed as the main method, there is no need to override main.

Hello World as a script

Scala can be used as a scripting language. To demonstrate, create HelloWorld.scala with the following content:

println("Hello")

Execute it with the command-line interpreter (the $ is the command line prompt):

$ scala HelloWorld.scala
Hello

If you omit .scala (such as if you simply typed scala HelloWorld) the runner will look for a compiled .class file with bytecode instead of compiling and then executing the script.

Note: If scala is used as a scripting language no package can be defined.

In operating systems utilizing bash or similar shell terminals, Scala scripts can be executed using a ‘shell preamble’. Create a file named HelloWorld.sh and place the following as its content:

#!/bin/sh
exec scala "$0" "$@"
!#
println("Hello")

The parts between #! and !# is the ‘shell preamble’, and is interpreted as a bash script. The rest is Scala.

Once you have saved the above file, you must grant it ‘executable’ permissions. In the shell you can do this:

$ chmod a+x HelloWorld.sh

(Note that this gives permission to everyone: read about chmod to learn how to set it for more specific sets of users.)

Now you can execute the script like this:

$ ./HelloWorld.sh

Using the Scala REPL

When you execute scala in a terminal without additional parameters it opens up a REPL (Read-Eval-Print Loop) interpreter:

nford:~ $ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_66).
Type in expressions for evaluation. Or try :help.

scala> 

The REPL allows you to execute Scala in a worksheet fashion: the execution context is preserved and you can manually try out commands without having to build a whole program. For instance, by typing val poem = "As halcyons we shall be" would look like this:

scala> val poem = "As halcyons we shall be"
poem: String = As halcyons we shall be

Now we can print our val:

scala> print(poem)
As halcyons we shall be

Note that val is immutable and cannot be overwritten:

scala> poem = "Brooding on the open sea"
<console>:12: error: reassignment to val
       poem = "Brooding on the open sea"

But in the REPL you can redefine a val (which would cause an error in a normal Scala program, if it was done in the same scope):

scala> val poem = "Brooding on the open sea"
poem: String = Brooding on the open sea

For the remainder of your REPL session this newly defined variable will shadow the previously defined variable. REPLs are useful for quickly seeing how objects or other code works. All of Scala’s features are available: you can define functions, classes, methods, etc.

Scala Quicksheet

Description Code
Assign immutable int value val x = 3
Assign mutable int value var x = 3
Assign immutable value with explicit type val x: Int = 27
Assign lazily evaluated value lazy val y = print("Sleeping in.")
Bind a function to a name val f = (x: Int) => x * x
Bind a function to a name with explicit type val f: Int => Int = (x: Int) => x * x
Define a method def f(x: Int) = x * x
Define a method with explicit typing def f(x: Int): Int = x * x
Define a class class Hopper(someParam: Int) { ... }
Define an object object Hopper(someParam: Int) { ... }
Define a trait trait Grace { ... }
Get first element of sequence Seq(1,2,3).head
If switch val result = if(x > 0) "Positive!"
Get all elements of sequence except first Seq(1,2,3).tail
Loop through a list for { x <- Seq(1,2,3) } print(x)
Nested Looping for {
  x <- Seq(1,2,3)
  y <- Seq(4,5,6)
} print(x + ”:” + y)
For each list element execute function List(1,2,3).foreach { println }
Print to standard out print("Ada Lovelace")
Sort a list alphanumerically List('b','c','a').sorted

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow