Adventures in CS

Scala Cheatsheet

09 Apr 2019

As I learn scala, I am going to update these notes for my own References


Lists are immutable

Empty List:

val list1 = List.empty[Int]


val list1 = List(10, 20, 30)
val list2 = 40 :: list1

Convert List[Any] to List[Int]:

# l is the list of Any datatype


val array = Array(1, 2, 3)
// append
val array1 = array :+ 4
// prepend
val array2 = 4 +: array


Sets come in two flavors: Mutable and immutable.

val fruit = Set("Apple", "Orange", "Peach", "Banana")
//adding elements
fruit += "Pineapple"
//Deleting elements
fruit -= "Orange"

There is SortedSet in scala as well


Scala has two types of HashMaps: Mutable and Immutable. Map() creates an immutable Map. In order to create mutable Map use scala.collection.mutable.Map()

var states = scala.collection.mutable.Map[String, String]()
// Adding elements
states += ("AZ" -> "Arizona", "KY" -> "Kentucky")
// removing elements
states -= "AZ"
// Update
states("KY") = "Kentucky, Chicken"


Using iterators

    val =


TypeTags help solve the type erasure problem.

import scala.reflect.runtime.universe._

def meth[A : TypeTag](xs: List[A]) = typeOf[A] match {
  case t if t =:= typeOf[String] => "list of strings"
  case t if t <:< typeOf[Foo] => "list of foos"

Here =:= is to check for type equality while <:< checks for subtype relation. More information can be found here


Ternary operator syntax: val a = if (i == 1) x else y


If an object doesn’t need to be serialized then use @transient lazy val. lazy val are fields that are evaluated once they are access for the first time and @transient denotes that a field shouldn’t be serialized.


To define a location you have to add something like this to the resolvers resolvers += "repository name" at "location" such as:

resolvers += " Maven2 Repository" at ""

Running a program:

If there is no need for command line arguments: sbt run

If specific class with command line parameters has to be executed then:

sbt "runMain param1 param2" or sbt "run-main param1 param2"


Tweet me @mb_ce if you like this post.

comments powered by Disqus