Scala

Scala was created by Martin Odersky at EPFL and released in 2004. Its name means "scalable language": the goal was to unify object-oriented and functional programming in one design instead of adding one to the other. Scala 3 was released in 2021 and simplified much of the syntax.

Paradigm: Object-Functional and Beyond

What Makes Scala Special

  • Everything is an object, every function is a value. Numbers have methods, and functions are objects you can pass around. Classes and closures mix freely.
  • Case classes and sealed traits. A case class is an immutable data class with equality and pattern matching. A sealed trait lists all its subtypes, so the compiler checks that match covers every case.
  • Traits as mixins. A class can extend several traits, each adding fields and methods. This gives multiple inheritance of behaviour without the diamond problem.
  • Immutable by default style. val is fixed, var is not, and the collections library favours immutable lists, maps and sets with rich map, filter and fold methods.
  • Givens and extension methods. Scala 3 given and using supply values implicitly (type classes), and extension adds methods to existing types.
  • Type inference and the JVM. Types are inferred where possible. Scala runs on the JVM with full Java interoperability, and also compiles to JavaScript (Scala.js) and native code (Scala Native).

Example: Sealed types, mixins and an extension method

sealed trait Shape
case class Circle(r: Double) extends Shape
case class Rect(w: Double, h: Double) extends Shape

def area(s: Shape): Double = s match
  case Circle(r)  => math.Pi * r * r
  case Rect(w, h) => w * h

trait Named:
  def name: String
  def greet: String = s"Hello, $name"

case class User(name: String) extends Named

extension (xs: List[Shape])
  def totalArea: Double = xs.map(area).sum

@main def run(): Unit =
  val shapes = List(Circle(1.0), Rect(2.0, 3.0))
  println(shapes.totalArea)              // 9.141592653589793
  println(shapes.filter(area(_) > 5))    // List(Rect(2.0,3.0))
  println(User("Ada").greet)             // Hello, Ada

How It Works

  • Shape is sealed, so all subtypes are known. If you add a Triangle and forget it in area, the compiler warns.
  • Named is a trait with a concrete method. User mixes it in and supplies name through its constructor parameter.
  • The extension block adds totalArea to any List[Shape] without changing the list class.
  • The last three lines mix styles: immutable list, functional filter with a placeholder lambda, and an object method call.

History and Where It Is Used

Scala is used for data processing (Apache Spark and Kafka are written in it), back-end services, and compilers and tools. It attracts teams that want strong static typing and functional style on the JVM. Compile times and the number of ways to do things are common complaints. The build tool is sbt, and Scala CLI runs single files quickly.

Learn More