Scala Classes & Objects
Learn object-oriented programming in Scala.
Class Definition
class Person(val name: String, var age: Int) {
// Class body
def greet(): String = s"Hello, my name is $name"
// Method with default parameter
def incrementAge(years: Int = 1): Unit = {
age += years
}
}
Object Instantiation
val alice = new Person("Alice", 25)
println(alice.greet()) // Hello, my name is Alice
alice.incrementAge()
println(alice.age) // 26
Companion Objects
class Circle(val radius: Double)
object Circle {
// Factory method
def apply(radius: Double): Circle = new Circle(radius)
def area(circle: Circle): Double =
math.Pi * circle.radius * circle.radius
}
val circle = Circle(5.0) // Using apply method
println(Circle.area(circle))
Case Classes
case class Point(x: Int, y: Int) {
def +(other: Point): Point =
Point(x + other.x, y + other.y)
}
val p1 = Point(1, 2)
val p2 = Point(3, 4)
val p3 = p1 + p2 // Point(4, 6)
Inheritance
abstract class Shape {
def area: Double
}
class Rectangle(width: Double, height: Double) extends Shape {
override def area: Double = width * height
}
class Circle(radius: Double) extends Shape {
override def area: Double = math.Pi * radius * radius
}
← Back to Tutorials