Skip to content

Scala

Overview

  • Developed by Martin Odersky
  • Statically typed
  • Supports object-oriented and functional programming paradigm
  • Sophisticated type inference system
  • Scala code results in .class files that run on the JVM
  • Interoperable with Java and Java libraries
object Hello extends App {
  println("hello world")
}
  • You compile scala code using scalac, similar to javac

REPL

  • Type scala to open the REPL

Variables

val x = 1   //immutable
var y = 0   //mutable
  • val is the similar to final in Java
  • You can create variables without declaring the type
  • Scala will then infer the type of that variable

Control structures

val x = if (a < b) a else b
  • If-else is an expression and returns a value, similar to the ternary operator
val result = i match {
    case 1 => "one"
    case 2 => "two"
    case _ => "not 1 or 2"
}
  • match is similar to switch-case
  • But it can also match on any data type
val booleanAsString = bool match {
    case true => "true"
    case false => "false"
}

Loops

// "for each"
for (arg <- args) println(arg)

// "x to y"
for (i <- 0 to 5) println(i)

// "x to y by"
for (i <- 0 to 10 by 2) println(i)

// yield keyword
val x = for (i <- 1 to 5) yield i * 2
  • yield creates a for-expression
  • There are also the usual while and do-while loops

Methods

// define methods
def sum(a: Int, b: Int): Int = a + b
def concatenate(s1: String, s2: String): String = s1 + s2

// call methods
val x = sum(1, 2)
val y = concatenate("foo", "bar")

Scala Build Tool (SBT)

  • Scala projects can be built with multiple tools like Ant, Maven, Gradle
  • sbt is a tool specifically created for Scala

Functional Programming

val nums = (1 to 10).toList

val doubles = nums.map(_ * 2)
val lessThanFive = nums.filter(_ < 5)

List("foo", "bar").map(s => s.toUpperCase)
List("foo", "bar").map(_.toUpperCase)

References


Last update: November 23, 2020