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
10: Classes and Objects
Up until now, we've spent a lot of time focusing on functions and data transformations. But as your projects grow, you'll find that grouping data and the logic that operates on that data into a single unit makes your code much easier to reason about. That's where classes and objects come in.
To keep this concrete, let's build a simple system to manage smart home devices. Specifically, we'll start with a smart light.
Drafting the SmartLight Blueprint
In Scala, a class is essentially a blueprint. I want every light in my house to have a name and a brightness level. I'll define these right in the primary constructor, which is that concise little block of code immediately following the class name.
class SmartLight(name: String, var brightness: Int) {
def setBrightness(level: Int): Unit = {
brightness = level
println(s"Setting $name to $level%")
}
def status(): String = {
s"Light $name is currently at $brightness%"
}
}
Notice I used var for brightness because that's something that's going to change. The name, however, stays the same, so I left it as a standard parameter. This looks clean, and it encapsulates the state and the behavior in one place.
Hitting a Wall with Scope
Now, I want to actually use this class in a program to see if it works. I'll instantiate a couple of lights and try to print their names.
val livingRoom = new SmartLight("Living Room", 70)
val kitchen = new SmartLight("Kitchen", 100)
println(livingRoom.name) // Error: value name is not a member of SmartLight
Wait, what happened? I defined name right there in the constructor. This is a classic Scala "gotcha" that I tripped over early in my career. In Scala, constructor parameters are private by default. They are available inside the class methods, but they aren't "fields" of the class unless you explicitly tell Scala to make them so.
To fix this, I just need to add the val keyword before name. This tells Scala: "Create a public, immutable field for this parameter."
class SmartLight(val name: String, var brightness: Int) {
// ... rest of the code stays the same
}
Now livingRoom.name works perfectly. It's a small distinction, but it's the difference between a local variable and a class member.
Managing Everything with a Singleton Object
Having individual light objects is great, but in a real app, you wouldn't just have floating variables everywhere. You'd likely have a central registry to track all your devices. Since we only ever need one registry for the entire application, a class isn't the right tool—a Scala object is.
In Scala, the object keyword creates a Singleton. It's a class that has exactly one instance, created lazily the first time it's accessed.
object DeviceRegistry {
private var devices = List.empty[SmartLight]
def registerDevice(device: SmartLight): Unit = {
devices = devices :+ device
println(s"Registered ${device.name}")
}
def listAllDevices(): Unit = {
println("Current Home Devices:")
devices.foreach(d => println(s"- ${d.name}"))
}
}
I made the devices list private because I don't want other parts of the code messing with the list directly; they should have to go through registerDevice. This is the heart of object-oriented design: controlling how state is modified.
Now we can tie it all together:
val light1 = new SmartLight("Bedroom", 50)
val light2 = new SmartLight("Hallway", 30)
DeviceRegistry.registerDevice(light1)
DeviceRegistry.registerDevice(light2)
DeviceRegistry.listAllDevices()📋 Practical Task
Build a Smart Thermostat Controller
Now it's your turn. You need to expand the smart home system by creating a thermostat controller. Follow these requirements:
- Create a class
SmartThermostatthat takes aval name: Stringand avar temperature: Doublein its constructor. - Add a method
setTemperature(newTemp: Double)that updates the temperature and prints a confirmation message. - Create a singleton
object ClimateControlthat maintains a list of all registered thermostats. - Implement a method in
ClimateControlcalledsetAllTo(temp: Double)that iterates through every registered thermostat and updates its temperature to the specified value. - In your main code, instantiate two different thermostats, register them with the
ClimateControlobject, and then usesetAllToto synchronize their temperatures.
There are no comments for now.