Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-21 03:24:25 Viewed : 261
In Scala, classes and objects are fundamental building blocks used for defining and creating reusable components. Here is an overview of classes and objects in Scala:
Classes:
new
keyword.scalaclass MyClass(var name: String, var age: Int) { def display(): Unit = { println(s"Name: $name, Age: $age") } }
Objects:
object
keyword.scalaobject MyObject { def myMethod(): Unit = { println("This is a method in MyObject") } }
Companion Objects:
scalaclass MyClass(var name: String, var age: Int) { def display(): Unit = { println(s"Name: $name, Age: $age") } } object MyClass { def apply(name: String, age: Int): MyClass = { new MyClass(name, age) } }
Understanding classes and objects is essential for creating and organizing complex applications in Scala. Classes define the structure and behavior of objects, while objects provide a way to group related methods and act as entry points or utility components in the application. Companions objects provide a convenient way to associate common functionalities with a class.
Example of a Class:
scalaclass Person(var name: String, var age: Int) { def display(): Unit = { println(s"Name: $name, Age: $age") } } // Creating an instance of the Person class val person = new Person("John", 30) person.display()
Output:
yamlName: John, Age: 30
Example of an Object:
scalaobject MathUtils { def square(x: Int): Int = x * x } // Accessing the method from the MathUtils object val result = MathUtils.square(5) println(result)
Output:
25
Example of a Class and its Companion Object:
scalaclass Person(var name: String, var age: Int) { def display(): Unit = { println(s"Name: $name, Age: $age") } } object Person { def apply(name: String, age: Int): Person = { new Person(name, age) } } // Creating an instance of the Person class using the companion object val person = Person("Alice", 25) person.display()
Output:
yamlName: Alice, Age: 25
In these examples, the first one demonstrates the usage of a simple class Person
, the second one showcases an object MathUtils
with a utility method, and the third one illustrates the usage of a companion object for the Person
class, providing a factory-like method apply
to create instances of the Person
class. Each example provides a clear understanding of how classes and objects work in Scala, along with their respective outputs.