Scala

Nick Tombeur - CGI Belgium

Why Scala?

  • JVM
  • Statically typed
  • Mixed paradigm
    • OOP
    • FP
  • Sophisticated type system
  • Elegant, flexible syntax
  • Scalable

Data types

Data type Description
Byte 8 bit signed value.
Short 16 bit signed value.
Int 32 bit signed value.
Long 64 bit signed value.
Float 32 bit IEEE 754 single-precision float
Double 64 bit IEEE 754 double-precision float
Char 16 bit unsigned Unicode character.
String A sequence of Chars
Data type Description
Boolean Either the literal true or the literal false
Unit Corresponds to no value
Null null or empty reference
Nothing The subtype of every other type; includes no values
Any The supertype of any type; any object is of type Any
AnyRef The supertype of any reference type

val - var

immutable - mutable

							
val name: Type = initialization // recommended
var name: Type = initialization
							
						

Demo

Conditional expressions

The entire if itself is an expression. Which means it produces a result.

							
if (expression) {
  /* ... */
} else if (expression) {
  /* ... */
} else {
  /* ... */
}
							
						

Demo

Compound Expressions

A compound expression can contain any number of other expressions, including other curly-braced expressions

						
{ expressions }
						
					

Demo

Methods & Functions

Functions are values; methods are not.

Methods

Evaluated, every time, on call.

							
def name(arg1: Type1, arg2: Type2): ReturnType = {
  /* ... */
}
							
						

Functions

Evaluated on initialization.

lazy val will evaluate on first call; only once.

							
(n: Int) => { /* ... */ }
							
						

Demo

Classes

							
class MyClass
val o = new MyClass
							
						

Fields

							
class Company(var name: String)
class Company(val name: String)
class Company(name: String)
class Company(private var name: String)
class Company(private val name: String)
class Company { val name = "CGI" }
							
						
Visibility Accessor / getter Mutator / setter
var Yes Yes
val Yes No
Default No No
private No No

Named & default arguments

							
// Named arguments
class Company(name: String, country: String)
new Company(name = "CGI", country = "Belgium")

// Default arguments
class Company(name: String = "CGI", country: String = "Belgium")
new Company("Telenet")
new Company(country = "Canada")
							
						

Overloading

							
class Foo {
  def bar() = /* ... */
  def bar(n: Int) = /* ... */
}
							
						

Note: overloading doesn't work in the REPL. Use REPL's :paste mode

Constructors

							
class Foo() {
  println("Called on creation")
}
							
						

Auxiliary constructors

							
class Point(x: Int, y: Int) {
  def this(x: Int) {
    this(x, 0)
  }
}
							
						

Case classes

							
								case class Name(arg1: Type, arg2: Type, ...)
							
						

Companion Objects

							
class Company() { /* ... */ }
object Company() { /* ... */ }
							
						

placeholder

more coming

Demo

Packages

						
// More than one within same statement
import util.Random, util.Properties
// Combining multiple classes in single statement
import util.{Random, Properties}
// Change name
import util.{ Random => HelterSkelter }
// Everything
import util._
						
					

Loops

For loops

							
for (var <- list) statement
for (var <- range) statement
for (var <- [range/list] if condition1; if condition2; ...) statement
							
						

While loops

							
while (condition) {
  /* ... */
}
							
						

Do While loop

							
do {
  /* ... */
} while (condition)
							
						

Demo

Collections

scala.collection

High-level abstract classes/traits

scala.collection.immutable

scala.collection.mutable

Best practice immutable/mutable

  • Prefer immutable
  • Use the mutable namespace explicitly
							
// Do
import scala.collection.mutable
val set = mutable.Set()

// Don't
import scala.collection.mutable._
val set = Set()
							
						

Common used

Type Description
Map key-value
Set no duplicate elements
List/Seq store elements and traverse them
Vector/IndexedSeq fast random selections and fast random functional updates

Demo

Pattern Matching

							
x match {
  case 1 => "one"
  case 2 => "two"
  case _ => "many"
}
							
						

With types

							
x match {
  case s: String => "A String"
  case i: Int if i < 10 => "An Int less than 10"
  case i: Int => "An Int"
  case c: Company => "A company"
}
							
						

With Case Classes

							
transport match {
  case Car(passengers, seats) => /* ... */
  case Bicycle(passengers, seats) => /* ... */
  case Passenger => /* ... */
}
							
						

String interpolation

						
val company = "CGI"
println(s"I am working for $company")

def foo = { 1 + 1 }
s"${foo}"
						
					

Tuples

						
(element1, element2, element3, ...)

val p = (1831, "Diegem")
p._1
p._2

val (postal, city) = p
						
					

Inheritance

                        
class Animal
class Bird extends Animal
class Ape extends Animal
                        
                    

Superclass Initialization

                            
class Animal(val age: Int)
class Bird(age: Int) extends Animal(age)
class Ape(age: Int, val weight: Double) extends Animal(age)
                            
                        

Overriding

							
class Bar {
  def run = 2
}

class Foo extends Bar {
  override def toString = "Hello World!"
  override def run = super.run * 2
}
							
						

Enumerations

						
object WeekDay extends Enumeration {
  type WeekDay = Value
  val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}