Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-08 05:18:06 Viewed : 600
Scala object and class
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.
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
}
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:
Example of a Scala Class:
scalaclass 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:
scalaval 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:
new
keyword.Example of a Scala Object:
scalaobject 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:
scalaval 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.