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 classis an immutable data class with equality and pattern matching. Asealed traitlists all its subtypes, so the compiler checks thatmatchcovers 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.
valis fixed,varis not, and the collections library favours immutable lists, maps and sets with richmap,filterandfoldmethods. - Givens and extension methods. Scala 3
givenandusingsupply values implicitly (type classes), andextensionadds 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
Shapeis sealed, so all subtypes are known. If you add aTriangleand forget it inarea, the compiler warns.Namedis a trait with a concrete method.Usermixes it in and suppliesnamethrough its constructor parameter.- The
extensionblock addstotalAreato anyList[Shape]without changing the list class. - The last three lines mix styles: immutable list, functional
filterwith 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.