Scala object and class

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-08 05:18:06 Viewed : 600


Scala object and class

·        Here is a simple class definition in Scala

class MyClassName{

}    

        var s = new MyClassName () // Creating an object

·        Define a  Scala class constructor 

class Employee(var firstName: String, var lastName: String) {

    def printFullName() = println(s"$firstName $lastName")

}

Notice that there is no need to create “get” and “set” methods to access the fields in the class.

Example:

Following example illustrates about Scala object and class

Save the file as −  Employee.scala. 


 Employee.scala 

package runnerdev 

class Employee {

  var id: Int = 11 // All fields must be initialized

  var name: String = "Ram"

}

object ClassAndObject {

  def main(args: Array[String]) {

    var s = new Employee() // Creating an object

    println(s.id + " " + s.name)

  }

compile and run the above example as follows 

scala> scalac Employee.scala

scala> scala Employee

OutPut:

11 Ram


Example:

Following example illustrates about Scala class constructor    

class Point(var x: Int, var y: Int) { 

  def move(dx: Int, dy: Int): Unit = {

    x = x + dx

    y = y + dy

  }

 override def toString: String =

    s"($x, $y)"

} 

val point1 = new Point(2, 3)

println(point1.x)  // 2

println(point1)  // prints (2, 3)


In Scala, both objects and classes are fundamental constructs used for defining and organizing code. They serve different purposes and have distinct characteristics. Here is an overview of Scala objects and classes:

1. Scala Class:

  • A class in Scala is a blueprint or template for creating objects.
  • It defines the structure and behavior of objects that will be created based on the class.
  • Classes can have fields (variables) and methods (functions) that describe the properties and behavior of the objects.
  • You can create multiple instances (objects) of a class.
  • Classes can have constructors, which are special methods used for initializing objects when they are created.
  • They support inheritance and can extend other classes (except for case classes).

Example of a Scala Class:

scala
class Person(name: String, age: Int) { // Class fields val fullName: String = name val yearsOld: Int = age // Method to display information def displayInfo(): Unit = { println(s"Name: $fullName, Age: $yearsOld") } }

To create an object from the above class:

scala
val person1 = new Person("Alice", 30) val person2 = new Person("Bob", 25) person1.displayInfo() // Output: Name: Alice, Age: 30 person2.displayInfo() // Output: Name: Bob, Age: 25

2. Scala Object:

  • An object in Scala is a singleton instance of a class. It is created automatically when the program starts and has only one instance throughout the applications lifecycle.
  • Objects are used to encapsulate utility functions, constants, or singletons that dont need multiple instances.
  • They are often used for defining entry points to applications and for creating utility methods and functions.
  • Objects cannot be instantiated explicitly using the new keyword.

Example of a Scala Object:

scala
object MathUtils { val Pi: Double = 3.14159265359 def add(x: Int, y: Int): Int = x + y def square(x: Double): Double = x * x }

To use the MathUtils object:

scala
val sum = MathUtils.add(5, 3) val area = MathUtils.Pi * MathUtils.square(2.0) println(s"Sum: $sum") println(s"Area: $area")

In summary, classes in Scala are used to define blueprints for creating multiple instances of objects with similar structures and behaviors, while objects are used to define singletons, utility methods, and constants. Both classes and objects play essential roles in Scalas object-oriented and functional programming paradigms.

Search
Related Articles

Leave a Comment: