Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-08 07:21:29 Viewed : 564
Scala constructor and method
In Scala, constructors and methods are fundamental components used to define classes and objects. Lets explore how constructors and methods work in Scala:
Constructors:
In Scala, constructors are used to initialize objects when they are created. Unlike some other programming languages, Scala allows you to have multiple constructors, known as primary and auxiliary constructors.
Primary Constructor:
The primary constructor is defined as part of the class definition. It is executed when you create an object of the class. Here is how you define a primary constructor:
scalaclass MyClass(param1: Int, param2: String) { // Code in the primary constructor println(s"Creating an object with param1: $param1 and param2: $param2") }
To create an instance of MyClass
, you simply call its constructor:
scalaval obj = new MyClass(42, "Hello")
Auxiliary Constructors:
Scala also allows you to define auxiliary constructors by using the this
keyword. These are additional constructors that provide different ways to initialize objects. Each auxiliary constructor must call either the primary constructor or another auxiliary constructor using the this
keyword. Here is an example:
scalaclass MyClass(param1: Int, param2: String) { def this(param1: Int) { this(param1, "Default") println("Auxiliary constructor with one parameter") } }
You can use auxiliary constructors like this:
scalaval obj1 = new MyClass(42)
Methods:
In Scala, methods are functions defined inside classes or objects. They can perform various operations on object data or return values. Here is how you define a method in Scala:
scalaclass MyClass { // Method definition def myMethod(param1: Int, param2: String): String = { s"Received param1: $param1 and param2: $param2" } }
To call a method on an object, you first create an instance of the class and then use the dot notation:
scalaval obj = new MyClass() val result = obj.myMethod(42, "Hello")
In this example, the myMethod
method takes two parameters (an integer and a string) and returns a string.
In summary, constructors in Scala are used to initialize objects when they are created, and methods are functions defined within classes or objects that can perform various operations and return values. Scala allows you to have multiple constructors, including a primary constructor and auxiliary constructors, to provide flexibility when initializing objects.
Here are examples of Scala constructors and methods along with their respective outputs:
Constructor Examples:
Primary Constructor:
Lets create a simple class Person
with a primary constructor:
scalaclass Person(firstName: String, lastName: String) { println(s"Creating a person: $firstName $lastName") }
Now, lets create an instance of the Person
class using the primary constructor:
scalaval person1 = new Person("John", "Doe")
Output:
cssCreating a person: John Doe
Auxiliary Constructor:
Here is a class Calculator
with a primary constructor and an auxiliary constructor:
scalaclass Calculator(initialValue: Int) { var result: Int = initialValue def this() { this(0) println("Calculator with default value created") } def add(value: Int): Unit = { result += value } }
Using the auxiliary constructor:
scalaval calculator1 = new Calculator() calculator1.add(5) val calculator2 = new Calculator(10) calculator2.add(7)
Output:
csharpCalculator with default value created
calculator1
uses the auxiliary constructor with a default value of 0, and calculator2
uses the primary constructor with an initial value of 10.
Method Examples:
Simple Method:
Let is define a class MathUtils
with a simple method to add two numbers:
scalaclass MathUtils { def add(a: Int, b: Int): Int = { a + b } }
Using the method:
scalaval mathUtils = new MathUtils() val sum = mathUtils.add(3, 7)
Output:
sum
will contain the value 10
.
Method with String Return:
Create a class StringUtils
with a method that concatenates two strings:
scalaclass StringUtils { def concatenate(str1: String, str2: String): String = { str1 + " " + str2 } }
Using the method:
scalaval stringUtils = new StringUtils() val result = stringUtils.concatenate("Hello", "World")
Output:
result
will contain the string "Hello World"
.
These examples demonstrate the use of constructors and methods in Scala. Constructors are used to initialize objects, and methods perform operations on those objects. The examples also show how objects are created and how methods are called, along with the expected outputs.
Just like other OOP languages, Scala classes have methods, and
this is what the Scala method syntax looks like:
·
Define a Scala class function(method )
def methodName(parameters : typeofparameters) : returntypeoffunction = {
// statements to be executed
}
object. methodName () //calling method name
· Define a Scala class constructor
class Employee(var firstName: String, var lastName: String) {
def printFullName() =
println(s"$firstName $lastName")
}
Just like other OOP languages, Scala classes have methods, and this is what the Scala method syntax looks like:
def sum(a: Int, b: Int): Int = a + b
def concatenate(s1: String, s2: String): String = s1 + s2
You
dont have to declare a methods return type, so it is perfectly legal to write
those two methods like this, if you prefer:
def concatenate(s1: String, s2: String) = s1 + s2
This is how you call those methods:
val x = sum(1, 2)
val y = concatenate("foo", "bar")
Following example illustrates about Scala constructor and method
Save the file as − ConstructorTest.scala.
package runnerdev
class EmployeeTest(id:Int, name:String){ // Primary
constructor
def display(){
println(id+" "+name)
}
}
object ConstructorTest{
def main(args:Array[String]){
var emp = new EmployeeTest(111,"Ram") // Passing values to constructor
emp.display() // Calling a function by using an
object
}
}
compile
and run the above example as follows
scala> scalac ConstructorTest.scala
scala> scala ConstructorTest
Output:
111 Ram
Example:
Following example illustrates about simple Scala functions
Save the file as − MethodCall.scala.
MethodCall.scala.
package runnerdev
object MethodCall {
def main(args: Array[String]) {
var result = functionExample() // Calling function
println(result)
}
def functionExample() = { // Defining a
function
var a = 10
a //Its a return
value
}
}
compile and run the above example as follows
scala> scalac MethodCall.scala
scala> scala MethodCall
Output:
10
Example:
Following example illustrates about Scala functions with params
Save the file as − MethodCall.scala.
MethodCall.scala
package runnerdev
object MethodCall {
def main(args: Array[String]) {
var result = functionExample() // Calling function
println("result " + result)
var a = 10
var b = 20
var addResult = functionExample(a, b) // Calling function
println("addResult
" + addResult)
}
def functionExample() = { // Defining a
function
var a = 10
a // or retunr a .Its a return value
}
def functionExample(a: Int = 0, b: Int = 0): Int = { // Parameters with
default values as 0
a + b
}
}
compile
and run the above example as follows
scala> scalac MethodCall.scala
scala> scala MethodCall
Output:
result 10
addResult 30