Scala — Cheat Sheet

Tags: scala, jvm, functional, object-oriented, typing

Level: intermediate

TL;DR: Scala elegantly combines object-oriented and functional programming paradigms on the JVM. It focuses on concise syntax, immutability by default, and powerful type safety.

Key concepts

-

Runs on the Java Virtual Machine (JVM) and interoperates seamlessly with existing Java code.

-

Treats every value as an object, including primitive types and functions.

-

Strongly encourages functional programming by favoring immutable values (val) and pure functions.

-

Features powerful type inference, reducing boilerplate code while maintaining strict static typing.

-

Uses case classes to provide structural equality, immutability, and native pattern matching.

-

Implements traits for mixin composition, allowing flexible multiple inheritance of behaviors.

-

Replaces Java's static members with companion objects (singletons sharing the exact class name).

-

Leverages implicit parameters and conversions to implement advanced patterns like type classes.

Typical questions and ready answers

-

Q: What is the exact difference between val and var in Scala?A: val creates an immutable reference that cannot be reassigned, whereas var creates a mutable reference. I always default to val.

-

Q: How does pattern matching work compared to a standard Java switch statement?A: It goes much further by allowing matching on types, destructuring data directly from case classes, and applying conditional guards.

-

Q: What is the main purpose of the Option type?A: It safely handles optional values using Some or None, forcing the compiler to check for missing values and eliminating null pointer exceptions.

Pitfalls and common mistakes

-

Defaulting to mutable collections or var variables instead of fully embracing functional immutability.

-

Over-engineering with complex implicit conversions, making the codebase unreadable and unpredictable.

-

Forgetting to use the @tailrec annotation on recursive functions, risking JVM stack overflow errors on large data sets.

Snippets and commands

// Case class definition
case class User(name: String, age: Int)

val user = User("Alice", 28)

// Advanced pattern matching with guards
user match {
  case User(n, a) if a >= 18 => println(s"$n is an adult.")
  case User(n, _) => println(s"$n is a minor.")
}

// Safe handling of optional values
val data: Option[String] = Some("Scala")
val result = data.getOrElse("Default value")

// Higher-order functions
val numbers = List(1, 2, 3, 4, 5)
val evens = numbers.filter(_ % 2 == 0).map(_ * 10)

To review

-

[ ] Differences in implicit resolution between Scala 2 and Scala 3 (given/using clauses).

-

[ ] Asynchronous programming using Future and Promise execution contexts.

-

[ ] Variance annotations (covariance +T and contravariance -T) in generic traits.

Jarvis Interviews
Jarvis