Welcome to the heart of Scala's Object-Oriented Programming (OOP) paradigm. In this tutorial, we'll delve into the foundation of Scala's OOP—Classes and Objects. These constructs form the building blocks for structuring and organizing code in a way that aligns with key OOP principles. Additionally, we'll explore the distinctive feature of Scala—Case Classes, providing concise and powerful tools for immutable data structures.
class Person(name: String, age: Int) {
def displayInfo(): Unit = {
println(s"Name: $name, Age: $age")
}
}
Person
is a class with parameters name
and age
.displayInfo
is a method within the class.val john = new Person("John", 30)
val alice = new Person("Alice", 25)
john.displayInfo() // Output: Name: John, Age: 30
alice.displayInfo() // Output: Name: Alice, Age: 25
Scala introduces a powerful and concise construct called Case Classes, tailored for immutable data structures.
case
keyword.case class Point(x: Int, y: Int)
Point
is a case class with parameters x
and y
.new
keyword.val origin = Point(0, 0)
val point = Point(1, 2)
println(origin) // Output: Point(0,0)
def processPoint(point: Point): String = {
point match {
case Point(0, 0) => "Origin"
case Point(_, 0) => "On X-axis"
case Point(0, _) => "On Y-axis"
case _ => "Somewhere in the plane"
}
}
match
expression makes pattern matching concise and readable.Classes and Objects in Scala provide a robust foundation for organizing code in an Object-Oriented manner. With the addition of Case Classes, Scala enables the creation of immutable data structures with concise syntax and enhanced functionality.
In the upcoming sections, we'll explore more advanced OOP concepts in Scala. Stay tuned for a deep dive into Traits, inheritance, and polymorphism as we continue to unlock the full potential of Scala's Object-Oriented Programming paradigm!