Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
43: Implementing a Linked List Functionally
When you first move from Java or Python to Scala, the way we handle lists can feel completely backwards. You're used to an ArrayList where you just call .add(). In a functional world, we don't "add" to a list; we create new versions of lists that share data with the old ones. It's a mental shift, but once it clicks, it makes your code significantly more predictable.
How do I actually define a list structure without using a mutable array?
We use a pattern called an Algebraic Data Type (ADT). Essentially, a linked list is either empty or it's a "cell" containing one element and a reference to the rest of the list. In Scala, we model this using a sealed trait and case classes.
sealed trait MyList[+A]
case object Nil extends MyList[Nothing]
case class Cons[A](head: A, tail: MyList[A]) extends MyList[A]
I use sealed here because it tells the compiler that Nil and Cons are the only two possible subtypes. This is huge for us later when we use pattern matching—the compiler will actually warn you if you've forgotten to handle the Nil case. The +A is a covariance annotation; it just ensures that a MyList[String] is also considered a MyList[Any], which makes the Nil object usable for any type of list.
If the list is immutable, does adding an item mean copying the whole thing?
This is the part that usually worries people. If you have a list of 10,000 items and you want to add one more, you might think you're duplicating those 10,000 items in memory. You aren't. We use something called structural sharing.
Because the list is immutable, we know the existing list will never change. So, to "add" an element to the front, we just create one new Cons cell that points to the existing list as its tail.
val original = Cons(1, Cons(2, Cons(3, Nil)))
val updated = Cons(0, original)
// 'updated' is now [0, 1, 2, 3], but it literally points to the same memory as 'original'
This is why prepending (adding to the front) is an $O(1)$ operation. Appending to the end, however, is a different story—you'd have to copy every single cell to update the final Nil to a Cons. In functional programming, we almost always prepend and then reverse the list if order matters.
How do I process the list without using a while loop?
Since we can't mutate a counter or an index, we use recursion and pattern matching. Think of it as peeling an onion: you handle the first element (the head), and then you call the same function on the rest of the list (the tail) until you hit Nil.
Let's say we want to sum a list of integers:
def sum(list: MyList[Int]): Int = list match {
case Nil => 0
case Cons(head, tail) => head + sum(tail)
}
It's clean, right? But there's a catch. Every time we call sum(tail), we push a new frame onto the call stack. If your list has 100,000 items, you're going to hit a StackOverflowError. I've spent way too many late nights debugging that exact issue.
How do I prevent the stack from overflowing on large lists?
The solution is Tail Recursion. We need to rewrite the function so that the recursive call is the very last thing the function does. We do this by introducing an "accumulator" to carry the running total along with us.
import scala.annotation.tailrec
def sumSafe(list: MyList[Int]): Int = {
@tailrec
def loop(remaining: MyList[Int], acc: Int): Int = remaining match {
case Nil => acc
case Cons(head, tail) => loop(tail, acc + head)
}
loop(list, 0)
}
By adding the @tailrec annotation, we're asking the Scala compiler to optimize this into a jump (basically a while loop under the hood). If the function isn't actually tail-recursive, the compiler will throw an error, which is a great safety net.
📋 Practical Task
Exercise: Implementing a Recursive List Reverser
In this exercise, you will implement a function to reverse a custom functional linked list. Remember that appending to the end of a functional list is expensive, but prepending is cheap. The most efficient way to reverse a list is to iterate through it and prepend each element to a new list (the accumulator).
Requirements:
- Define the
MyList[+A]trait,Nilobject, andConsclass as shown in the lesson. - Write a function
reverseList[A](list: MyList[A]): MyList[A]. - The implementation must be tail-recursive. Use the
@tailrecannotation to ensure the compiler optimizes it. - Test your function with a list of at least 5 elements (e.g.,
Cons(1, Cons(2, Cons(3, Cons(4, Cons(5, Nil)))))) and verify the order is inverted.
There are no comments for now.