Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Class and Object in Scala

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:

1. Class:

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.")
  }
}

2. Object Instantiation:

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.

3. Primary Constructor:

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.

4. Auxiliary 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.

5. Object:

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.

6. Companion Object:

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

7. Apply Method:

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.

8. Case Classes:

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.

  1. Defining classes in Scala:

    • Description: Classes in Scala encapsulate data and behavior. They can have fields and methods.
    • Code Example:
      class Person(var name: String, var age: Int) {
        def greet(): Unit = {
          println(s"Hello, my name is $name and I am $age years old.")
        }
      }
      
  2. Scala object-oriented programming basics:

    • Description: Object-oriented programming (OOP) in Scala involves creating classes and objects, encapsulating state and behavior.
    • Code Example:
      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()}")
      
  3. Creating objects in Scala:

    • Description: Objects are instances of classes. They encapsulate the state defined by the class.
    • Code Example:
      class Point(var x: Int, var y: Int)
      
      val myPoint = new Point(3, 5)
      println(s"Coordinates: (${myPoint.x}, ${myPoint.y})")
      
  4. Scala case classes and objects:

    • Description: Case classes in Scala are used for immutable data modeling. They come with built-in equals, hashCode, and toString methods.
    • Code Example:
      case class Person(name: String, age: Int)
      
      val john = Person("John", 30)
      val jane = Person("Jane", 25)
      
      println(john == jane) // false
      
  5. Inheritance in Scala classes:

    • Description: Inheritance allows a class to inherit fields and methods from another class.
    • Code Example:
      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!")
        }
      }
      
  6. Abstract classes and traits in Scala:

    • Description: Abstract classes and traits define common behavior that can be shared among multiple classes.
    • Code Example:
      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
      }
      
  7. Singleton objects in Scala:

    • Description: Singleton objects are used to define methods and fields that are shared across all instances of a class.
    • Code Example:
      object Logger {
        def log(message: String): Unit = {
          println(s"Log: $message")
        }
      }
      
      Logger.log("An important message")
      
  8. Companion objects in Scala:

    • Description: Companion objects are objects with the same name as a class. They share the same scope and can access each other's private members.
    • Code Example:
      class Circle(radius: Double) {
        import Circle._
        def area(): Double = pi * radius * radius
      }
      
      object Circle {
        private val pi: Double = 3.14
      }
      
  9. Object-oriented features in Scala:

    • Description: Scala supports various OOP features, including encapsulation, inheritance, polymorphism, and abstraction.
    • Code Example:
      abstract class Animal {
        def makeSound(): Unit
      }
      
      class Dog extends Animal {
        def makeSound(): Unit = println("Woof!")
      }
      
  10. Encapsulation in Scala classes:

    • Description: Encapsulation involves hiding the internal details of a class and exposing only what is necessary.
    • Code Example:
      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
      }
      
  11. Scala class fields and methods:

    • Description: Class fields store the state, while methods define behavior. Fields and methods are accessed using object instances.
    • Code Example:
      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()}")
      
  12. Using classes and objects for code organization in Scala:

    • Description: Classes and objects help organize code by encapsulating related behavior and state.
    • Code Example:
      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)
      }