Scala programming language

Updated: 2019-09-11 by Pradeep Gowda.

See Also: Scala for Datascience, ScalaJS

July, 2015 – Scala book reviews Feb, 2018 – Recursion and Trampolines in Scala

Notes from Programming in Scala

Chapter 7 - built-in control structures.

def pyFiles =
  for {
    file <- files
    if file.getName.endsWith('.py')
  } yield file


try {

} catch {
  case ex: FileNotFoundException => //handle
  case ex: IOException => //handle


val fruit =
    someArg match {
      case "foo" => "bar"
      case "banana" => "pepper"
      case _ => "what?"

Chapter 8- Functions and Closures

First class functions

(x: Int) => x+1

named function:

var increase = (x: Int) => x + 1

Placeholder syntax:

someNumbersList.filter( _ > 0)
val f = (_: Int) + (_: Int)

Chapter 12 – Traits

Traits are like java interfaces with concrete methods + declare fields and maintain state.

Traits can do everything classes can do, except –

  1. trait cannot have any clas parameters (ie., those passed to primary constructors).
  2. super calls are not statically bound.

Unlike Java, adding a concrete method to scala trait is an one-time effort.

Chapter 15 – Case classes and pattern matching

Notes from “Scala in Action”

Chapter 2 – Getting started

// working with arrays and Lists
@ val nList = 1 :: 2 :: 3 :: 4 :: Nil
nList: List[Int] = List(1, 2, 3, 4)
@ nList.fil
filter     filterNot
@ nList.filter( _ > 2)
res17: List[Int] = List(3, 4)

@ // for comprehensions
@ oldList
res19: List[Int] = List(1, 2)
@ newList
res20: List[Int] = List(1, 2, 3)
@ for { a <- oldList; b <- newList } println (a+b)
@ // above is imperative form
@ // The functional form for comprehension is:
@ // also called the sequence composition
@ for { a <- oldList; b <- newList } yield a+b
res22: List[Int] = List(2, 3, 4, 3, 4, 5)

@ // Pattern Matching
@ val x = 3
x: Int = 3
@ def ordinal(number: Int):  Unit = number match {
    case 0 => println("One")
    case 1 => println("Two")
    case 2 => println("Three")
    case 3 => println("Four")
    case _ => println("what is this?")
defined function ordinal
@ ordinal(x)

@ // Pattern Matching Types
@ dBef printType(obj: AnyRef) = obj match {
    case s: String => println("This is a string")
    case i: java.util.Date => println("This is a Date")
    case l: List[_] => println("An array eh?")
    case _ => println("dunno who ye are")
defined function printType
@ printType(List(1,1,2))
An array eh?

// Guards
@ def numCatcher(num: Int): Unit = num match {
    case x if x < 10 => println("Number less than 10")
    case y if (y%2 == 0) => println("Is an even number")
defined function numCatcher
@ numCatcher(5)
Number less than 10

@ numCatcher(12)
Is an even number

Miscellaneous notes

sbt plays an important role in the day to day programming of scala. I believe ‘sbt’ stood for “scala build tool” at one time, but is no longer.

To start working on a scala program, you can start with a simple text editor, however using something like IntelliJ IDEA is probably far more productive.

Creating a “project structure” can be automated. Essentially this boilBs down to creating the build.sbt file, project directory and optional plugins.sbt file inside it, a scala file inside the proper src/main/scala/com/example/projectname/ directory etc., There is little reason to do all this manually, except when you are trying to understand the reason behind such a recommended directory layout.

giter8 ie., the g8 is a tool that can create a project structure based on pre-defined templates. Think of this as paster tool for Python.

When you have g8 installed, creating a new project (say, a basic scala project using this template ), all you have to do is:

$ g8 fayimora/basic-scala-project.g8

A basic scala project

name [Basic Project]: basic-scala
organization [com.example]: com.btbytes
version [0.0.1]:

Template applied in ./basic-scala

$ cd basic-scala
$ ls
build-sbt src

$ sbt run will download the dependencies defined in the build.sbt file,B compile source and run the program.

sbt can also create the files necessary to make this an “IntelliJ IDEA project”. For this, we add a dependency to the plugins.sbt file:

#project/plugins.sbt -- add this line
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.6.0")

Running sbt gen-idea will generate the IDEA project files (.idea, some .iml).

Launch up IDEA and “open project” and open the root directory of the project. You are now set to work on the code.

Packaging the binary to a .jar:

$ sbt packageBin

Will produce target/scala-2.10/basic-scala_2.10-0.0.1.jar (where basic-scala is the name of the project).

Why not Scala


Covariance, Contravariance and Invariance


In general, covariant type parameter can be used as immutable field type, method return type and also as method argument type if the method argument type has a lower bound. Because of those restrictions, covariance is most commonly used in producers (types that return something) and immutable types.

Adhoc polymorphism

In this article we discussed the motivation for introducing ad hoc polymorphism and implementing it using the Type Class Pattern in Scala. It allows us to build abstractions which are completely decoupled from the underlying data types on which they operate. Hence we can implement polymorphic functions which operate on types we have no control over, such as types defined in the standard library or some other third party library, without sacrificing the static type safety.

Concurrency (Akka etc.,)





Ensime – Enhanced Scala

Interaction Mode for Emacs.






Ammonite REPL is much more featureful than the default REPL and comes with a lot of ergonomic improvements and configurability that may be familiar to people coming from IDEs or other REPLs such as IPython or Zsh.


Scala Native



Indyscala notes

Feb 6, 2017 – Resource management in Scala

Presenter – Ross A. Baker

May 1, 2017