Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
Scala, being both an object-oriented and functional language, provides a rich system for defining classes and objects. Here's a comprehensive tutorial on understanding and using classes and objects in Scala:
A class is a blueprint for creating objects. It encapsulates data and methods that operate on the data.
class Person(name: String, age: Int) { def greet(): Unit = { println(s"Hello, my name is $name and I am $age years old.") } }
You create an instance of a class using the new
keyword:
val john = new Person("John", 25) john.greet() // Outputs: Hello, my name is John and I am 25 years old.
The primary constructor of a class is interwoven with the class definition itself. In the Person
example, (name: String, age: Int)
is the primary constructor.
Classes can also have auxiliary constructors, which need to start with the def this()
notation:
class Person(name: String, age: Int) { def this(name: String) = this(name, 0) // An auxiliary constructor def greet(): Unit = { println(s"Hello, my name is $name and I might be $age years old.") } } val unknownAgePerson = new Person("Alice") unknownAgePerson.greet() // Outputs: Hello, my name is Alice and I might be 0 years old.
Scala has a unique feature called object
. It serves as both a companion to a class and a singleton instance of its own type.
object MathUtility { def add(x: Int, y: Int): Int = x + y } val result = MathUtility.add(5, 3) // Uses the singleton instance, no need to instantiate.
When an object
has the same name as a class
and is defined in the same source file, it's called a companion object. The class and its companion object can access each other's private members.
class Calculator(val brand: String) object Calculator { def info(c: Calculator): String = s"This is a calculator of brand: ${c.brand}" } val calc = new Calculator("Casio") println(Calculator.info(calc)) // This is a calculator of brand: Casio
A common idiom in Scala is to use the apply
method in companion objects to provide a neat way to construct instances:
class Person(name: String, age: Int) object Person { def apply(name: String, age: Int): Person = new Person(name, age) } val sam = Person("Sam", 28) // Behind the scenes, this calls the apply method of the Person object.
Scala provides a handy shortcut for creating classes with immutable data, automatic equals
, hashCode
, toString
, and copy methods: case classes.
case class Car(brand: String, model: String) val car1 = Car("Toyota", "Corolla") println(car1) // Outputs: Car(Toyota,Corolla)
In conclusion, classes and objects in Scala provide a rich system for object-oriented programming. This tutorial only scratches the surface. As you explore more, you'll find features like inheritance, traits, abstract classes, and more, all of which combine to give you a powerful toolkit for OOP in Scala.
Defining classes in Scala:
class Person(var name: String, var age: Int) { def greet(): Unit = { println(s"Hello, my name is $name and I am $age years old.") } }
Scala object-oriented programming basics:
class Circle(radius: Double) { val pi: Double = 3.14 def area(): Double = pi * radius * radius } val myCircle = new Circle(5.0) println(s"Area of the circle: ${myCircle.area()}")
Creating objects in Scala:
class Point(var x: Int, var y: Int) val myPoint = new Point(3, 5) println(s"Coordinates: (${myPoint.x}, ${myPoint.y})")
Scala case classes and objects:
case class Person(name: String, age: Int) val john = Person("John", 30) val jane = Person("Jane", 25) println(john == jane) // false
Inheritance in Scala classes:
class Animal(var species: String) { def makeSound(): Unit = { println("Some generic animal sound") } } class Dog(species: String, var breed: String) extends Animal(species) { override def makeSound(): Unit = { println("Woof!") } }
Abstract classes and traits in Scala:
abstract class Shape { def area(): Double } trait Color { val color: String } class Circle(radius: Double, val color: String) extends Shape with Color { def area(): Double = math.Pi * radius * radius }
Singleton objects in Scala:
object Logger { def log(message: String): Unit = { println(s"Log: $message") } } Logger.log("An important message")
Companion objects in Scala:
class Circle(radius: Double) { import Circle._ def area(): Double = pi * radius * radius } object Circle { private val pi: Double = 3.14 }
Object-oriented features in Scala:
abstract class Animal { def makeSound(): Unit } class Dog extends Animal { def makeSound(): Unit = println("Woof!") }
Encapsulation in Scala classes:
class BankAccount(private var balance: Double) { def deposit(amount: Double): Unit = { if (amount > 0) balance += amount } def withdraw(amount: Double): Unit = { if (amount > 0 && amount <= balance) balance -= amount } def getBalance: Double = balance }
Scala class fields and methods:
class Rectangle(var length: Double, var width: Double) { def area(): Double = length * width } val myRectangle = new Rectangle(5.0, 3.0) println(s"Area of the rectangle: ${myRectangle.area()}")
Using classes and objects for code organization in Scala:
object MathUtils { def square(x: Double): Double = x * x } class Calculator { def add(a: Double, b: Double): Double = a + b def squareRoot(x: Double): Double = Math.sqrt(x) }