We use only a basic subset of Scala in the book. Here is the chronological summary of all the Scala features we use in the book. You can look at them in your editor by going to the chA_ScalaCheatSheet.scala file in the book’s code repository. Make sure to look at the README.md file, too.
Defining a value
val x: Int = 2022 ①
val y: String = "YYY" ①
val z = true ①
① You can define the expected type of your value using : , but you don’t have to do it, and the compiler will try to infer it for you. Here, the inferred type of z is Boolean .
Defining a function
def f(a: Int): Int = {
a + 1 ①
}
def g(a: Int, b: String): Boolean = {
a == b.length && z ②
}
① Semicolons are not required, nor is the return keyword.
② Values are compared using ==. Here, the logical && operator is part of the last expression in the function body, which becomes the returned result.
Calling a function
f(x)
→ 2023
g(x, y)
→ false
Creating immutable collections
val list: List[Int] = List(1, 2, 3)
val set: Set[String] = Set("Hello", "World")
Passing a function by name
list.map(f)
→ List(2, 3, 4)
Passing an anonymous function
list.filter(i => i > 1) ①
→ List(2, 3)
① We define a function using the double-arrow operator.
Passing an anonymous two-parameter function
list.foldLeft(2020)((sum, i) => sum + i)
→ 2026
Defining functions with multiple parameter lists (currying)
def h(a: Int)(b: List[Int]): Boolean = {
b.contains(a) ①
}
val foo: List[Int] => Boolean = h(2020) ②
① Applying arguments only for a single parameter list returns another function.
② A => B is a type of a function that takes A and returns B .
Math
Math.max(Int.MinValue, 2022) ①
→ 2022
① Math operations are defined in the Math object. Type numerical boundaries can be obtained using the MinValue and MaxValue fields.
Defining a case class (product type) and creating its value
case class Book(title: String, numberOfChapters: Int)
val grokkingFp = Book("Grokking Functional Programming", 12)
The dot syntax for accessing values in a case class
val books: List[Book] = List(grokkingFp, Book("Ferdydurke", 14))
books.filter(book => book.numberOfChapters > 13)
→ List(Book("Ferdydurke", 14))
The underscore syntax for defining anonymous functions
books.filter(_.numberOfChapters > 13) ①
→ List(Book("Ferdydurke", 14))
① This is equivalent to the filter usage in the section above.
Missing implementation: ???
def isThisBookAnyGood(book: Book) = ??? ①
① This code compiles, but it will throw an exception if someone calls it (for any book, not just this one!).
String interpolation
s"Reading ${grokkingFp.title} now!" ①
→ "Reading Grokking Functional Programming now!" ①
① If you want to create a multi-line String value, you can use triple quotes: """text""" . String interpolation is possible there, too (add an s before).
Passing a multi-line function
books.map(book =>
if (book.numberOfChapters > 12)
s"${book.title} is a long book" ①
else
s"${book.title} is a short book"
)
→ List("Grokking Functional Programming is a short book",
"Ferdydurke is a long book")
① You don’t have to use braces if your indentation is correct.
Type inference and empty lists
val emptyList1 = List.empty[Int] ①
val emptyList2: List[Int] = List.empty ①
① Both definitions of a value holding an empty list of integers are equivalent. You can always help the compiler this way.
Type inference and forcing the type
val listOfDoubles1 = List[Double](1, 2, 3)
val listOfDoubles2: List[Double] = List(1, 2, 3) ①
① Without setting the type, the compiler would infer a List[Int] .
Defining a for comprehension
for {
i <- List(1, 2)
book <- books
} yield s"Person #$i read ${book.title}"
→ List("Person #1 read Grokking Functional Programming",
"Person #1 read Ferdydurke",
"Person #2 read Grokking Functional Programming",
"Person #2 read Ferdydurke")
Objects as modules and object as “bags” for types and functions
object things {
case class Thing(value: Int, description: String)
def inflate(thing: Thing): Thing = ①
thing.copy(value = thing.value + 2030) ②
}
things.inflate(things.Thing(3, "Just a thing")) ③
→ Thing(2033, "Just a thing")
① We can bundle types and functions inside well-named objects.
② You can copy a case class value by providing only fields you want to change, using the copy function.
③ They are publicly available using the dot syntax.
Defining an opaque type (newtype)
object model {
opaque type BookRating = Int ①
object BookRating { ②
def apply(rawRating: Int): BookRating = ②
Math.max(0, Math.min(5, rawRating)) ②
extension (a: BookRating) def value: Int = a ③
}
}
① We can define opaque types that are zero-cost wrappers around primitive types.
② In their companion object ( object with the same name) we can define the apply function, which is called when creating a new value based on the underlying primitive value.
② By default, an opaque type doesn’t inherit any functionalities from its underlying type. We can add them by providing extension methods.
Importing everything from an object using underscore
import model._
Creating and using a value of an opaque type
val rating: BookRating = BookRating(5) ①
rating / 2
→ Error: rating / 2 value / is not a member of model.BookRating ②
val i = rating.value / 2 ③
→ i: Int = 2
① Creating a BookRating from an Int value ( apply is called)
② You can’t use rating as any Int even though it’s just an Int underneath.
③ You need to use an extension method (the value here returns the underlying Int ).
Defining enums (sum types)
enum BookProgress {
case ToRead ①
case Reading(currentChapter: Int) ①
case Finished(rating: BookRating) ①
}
import BookProgress._
① Each of the three types are subtypes of BookProgress . ToRead is a singleton type, while Reading and Finished are product types with one field. You can create bigger cases.
Pattern matching
def bookProgressUpdate(book: Book, bookProgress: BookProgress): String = {
bookProgress match {
case ToRead =>
s"I want to read ${book.title}"
case Finished(rating) => ①
s"I just finished ${book.title}! It's $rating/5!"
case Reading(currentChapter) => ②
if (currentChapter <= book.numberOfChapters / 2)
s"I have started reading ${book.title}"
else
s"I am finishing reading ${book.title}"
}
}
① We can destructure a value into its internal values.
② The compiler checks whether we provided a case for each possible item in the enum . All expressions to the right of the => operator need to have the same type (here, String ).
Naming parameters in class constructors and functions
val b = Book(title = "Grokking Functional Programming",
numberOfChapters = 12)
bookProgressUpdate(book = b, bookProgress = Reading(currentChapter = 13)) ①
→ "I am finishing reading Grokking Functional Programming"
① It’s true, you know! And thanks for reading it all!
Using trait s as bags for function blueprints
trait BagOfFunctions { ①
def f(x: Int): Boolean
def g(y: Book): Int
}
① A value of type BagOfFunctions will provide two functions.
Creating trait instances (bags of functions)
val bagOfFunctions = new BagOfFunctions { ①
def f(x: Int): Boolean = x == 1
def g(y: Book): Int = y.numberOfChapters * 2
}
bagOfFunctions.f(2020) ②
→ false
① We are creating a value of type BagOfFunctions by using the new keyword and providing implementations for the two required functions.
② We can access each of the internal functions using the dot syntax.
Unit value in Scala
val unit: Unit = () ①
① There is only a single value of type Unit in Scala: () . Nobody can create another value. This type is returned from functions that don’t return anything constructive (they usually cause a lot of side effects).
Creating a Map immutable type
val book1 = Book("Grokking Functional Programming", 12)
val book2 = Book("Ferdydurke", 14)
val progressPerBook: Map[Book, BookProgress] = Map(
book1 -> Reading(currentChapter = 13),
book2 -> ToRead
)
Passing functions that pattern match
progressPerBook.values.filter(bookProgress => ①
bookProgress match {
case ToRead => false ②
case Reading(_) => false
case Finished(_) => true
}
)
→ List.empty
progressPerBook.values.filter(_ match { ③
case ToRead => false
case Reading(_) => false
case Finished(_) => true
})
→ List.empty
progressPerBook.values.filter { ③
case ToRead => false
case Reading(_) => false ④
case Finished(_) => true
}
→ List.empty
① You can use the Map.values function to return a list of values held in the Map (here, BookState s).
② We use a subset of Scala syntax in the book because our focus is FP. That’s why we usually stick to writing functions using the familiar => operator, even when all they do is pattern matching.
③ Alternatively, you can write exactly the same code using a more concise syntax.
④ You can ignore destructured values by not naming them and using the underscore to indicate that.
Not naming values using underscore
for {
_ <- List(1, 2, 3)
book <- List(Book("A", 7), Book("B", 13))
} yield book.numberOfChapters
→ List(7, 13, 7, 13, 7, 13)
Durations and big numbers
import scala.concurrent.duration._
val duration: FiniteDuration = 1.second ①
val durations: List[FiniteDuration] =
List(100.millis, 2.seconds, 5.minutes, 500_000.hours) ②
① You can use an underscore inside numbers to make them more readable.
② You can use this concise syntax to create FiniteDuration immutable values, which are used universally in time-based functions and types.