
Unraveling Object-Oriented Basics in Scala
This blog is part of a 10-part series designed to help readers learn Scala from the ground up. Whether you’re new to Scala or looking to solidify your understanding, this series will guide you through its core concepts step by step.
Scala’s seamless integration of object-oriented and functional programming paradigms makes it a unique and powerful language. In this post, we’ll explore essential object-oriented programming (OOP) concepts in Scala, including classes, objects, inheritance, and more, through unique and engaging examples.
Classes and Objects
Classes in Scala define blueprints for objects, encapsulating state and behavior. Here’s an example:
object OOPBasics extends App { val user = new User("Alice", 28) user.introduce() // OUTPUT: Hi, I am Alice. user.introduce("Bob") // OUTPUT: Alice says: Hello, Bob! val book = new Book("Scala Adventures", 2023, new Author("John", "Doe", 1985)) println(book.authorAge) // OUTPUT: 38 println(book.isWrittenBy(new Author("John", "Doe", 1985))) // OUTPUT: false val counter = new Counter(5) println(counter.increment(3).count) // OUTPUT: 8 println(counter.decrement(2).count) // OUTPUT: 3 } class User(val name: String, val age: Int) { def this(name: String) = this(name, 0) def introduce(): Unit = println(s"Hi, I am $name.") def introduce(otherName: String): Unit = println(s"$name says: Hello, $otherName!") } class Book(title: String, year: Int, author: Author) { def authorAge: Int = year - author.yearOfBirth def isWrittenBy(author: Author): Boolean = author == this.author def copy(newYear: Int): Book = new Book(title, newYear, author) } class Author(val firstName: String, val lastName: String, val yearOfBirth: Int) { def fullName: String = s"$firstName $lastName" } class Counter(val count: Int) { def increment(by: Int = 1): Counter = new Counter(count + by) def decrement(by: Int = 1): Counter = new Counter(count - by) }
Key Takeaways
- Primary Constructor: Defined in the class signature.
- Auxiliary Constructors: Provide alternative ways to instantiate classes.
- Encapsulation: Fields and methods can be marked private or protected.
Singleton Objects
Scala uses object to define singletons, which are classes with a single instance. Singleton objects are useful for utility methods and factory patterns.
object UserFactory { def createDefaultUser(): User = new User("DefaultUser", 25) } val defaultUser = UserFactory.createDefaultUser() defaultUser.introduce() // OUTPUT: Hi, I am DefaultUser.
Companion Objects
A companion object shares the same name as its class and can access its private members.
class User(val name: String, val age: Int) object User { // COMPANION OBJECT def apply(name: String, age: Int): User = new User(name, age) } val user = User("Eve", 30)
Inheritance and Polymorphism
Inheritance allows classes to reuse and extend functionality. Scala supports single-class inheritance and type substitution (polymorphism).
class Animal { def sound(): Unit = println("Some generic sound") } class Dog extends Animal { override def sound(): Unit = println("Bark") } val myDog: Animal = new Dog myDog.sound() // Output: Bark
Access Modifiers
- private: Accessible only within the class.
- protected: Accessible within the class and its subclasses.
- public (default): Accessible everywhere.
Preventing Overrides
- Use final on methods or classes.
- Use sealed to restrict inheritance to the same file.
Case Classes
Case classes are immutable and come with built-in functionality like equality checks, serialization, and pattern matching.
case class Point(x: Int, y: Int) val point1 = Point(1, 2) val point2 = Point(1, 2) println(point1 == point2) // Output: true
Conclusion
Scala’s OOP features, combined with its functional capabilities, provide developers with a versatile toolkit. Understanding classes, objects, inheritance, and case classes is crucial for building robust and maintainable applications. Whether you’re managing state or leveraging polymorphism, Scala’s OOP features ensure you can write elegant and powerful code.
Happy coding!
Pizenith is a trusted technology partner specializing in Data Engineering, Machine Learning, AI, Cloud Engineering, DevOps, and Functional Programming with Scala and Java. We help businesses scale with secure, automated, and data-driven solutions, delivering innovation in Test Automation and DevSecOps. Trusted by global enterprises, we empower organizations to stay ahead with AI-powered insights and scalable cloud infrastructure.
Want to future-proof your tech stack? Let’s talk! or reach us at info@pizenith.com.