Skip to Content
Course content

10: Classes and Objects

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 SmartThermostat that takes a val name: String and a var temperature: Double in its constructor.
  • Add a method setTemperature(newTemp: Double) that updates the temperature and prints a confirmation message.
  • Create a singleton object ClimateControl that maintains a list of all registered thermostats.
  • Implement a method in ClimateControl called setAllTo(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 ClimateControl object, and then use setAllTo to synchronize their temperatures.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.