Object-Oriented Programming (OOP) Basics in Scala
In this lesson, you will learn the fundamentals of Object-Oriented Programming (OOP) in Scala. OOP is a programming paradigm that organizes code using objects and classes.
Scala supports both object-oriented and functional programming, making it a powerful hybrid language.
What Is Object-Oriented Programming?
Object-Oriented Programming is based on the idea of representing real-world entities as objects.
Each object:
- Contains data (fields)
- Performs actions (methods)
This approach helps build scalable and maintainable applications.
Classes in Scala
A class is a blueprint used to create objects. It defines the structure and behavior of objects.
class Person(name: String, age: Int)
This class defines two parameters: name and age.
Creating Objects
Objects are instances of a class.
In Scala, objects are created using the new keyword.
val p = new Person("Alice", 25)
This creates a new object of the Person class.
Class Fields and Methods
Classes can contain fields and methods.
class Person(val name: String, val age: Int) {
def greet(): String = {
s"Hello, my name is $name"
}
}
Here:
nameandageare fieldsgreet()is a method
Accessing Methods
You can call methods on objects using dot notation.
val p = new Person("Bob", 30)
println(p.greet())
This prints a greeting message.
The val vs var in Classes
Fields defined with val are immutable, while var fields
are mutable.
class Counter(var count: Int) {
def increment(): Unit = {
count += 1
}
}
Use val whenever possible to avoid unintended changes.
Objects in Scala
Scala provides a special construct called object. An object is a singleton — only one instance exists.
object Utils {
def add(a: Int, b: Int): Int = a + b
}
You can call methods on objects directly.
println(Utils.add(3, 4))
Companion Objects
A companion object shares the same name as a class and can access its private members.
class MathUtil(val value: Int)
object MathUtil {
def square(x: Int): Int = x * x
}
This pattern is commonly used in Scala.
Encapsulation in Scala
Encapsulation means restricting direct access to data.
class BankAccount(private var balance: Double) {
def deposit(amount: Double): Unit = {
balance += amount
}
def getBalance: Double = balance
}
This protects the internal state of the object.
Why OOP Matters in Scala
OOP allows you to:
- Model real-world entities
- Reuse code effectively
- Build scalable applications
Scala blends OOP with functional programming for maximum flexibility.
📝 Practice Exercises
Exercise 1
Create a class Car with fields for brand and year.
Exercise 2
Add a method that prints car details.
Exercise 3
Create an object with a utility function.
✅ Practice Answers
Answer 1 & 2
class Car(val brand: String, val year: Int) {
def info(): String = s"$brand - $year"
}
Answer 3
object CarUtils {
def isNew(year: Int): Boolean = year >= 2020
}
What’s Next?
In the next lesson, you will learn about Constructors in Scala, including primary and auxiliary constructors.