Scala constructor and method

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.

  1. 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:

    scala
    class 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:

    scala
    val obj = new MyClass(42, "Hello")
  2. 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:

    scala
    class 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:

    scala
    val 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:

scala
class 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:

scala
val 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:

  1. Primary Constructor:

    Lets create a simple class Person with a primary constructor:

    scala
    class 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:

    scala
    val person1 = new Person("John", "Doe")

    Output:

    css
    Creating a person: John Doe
  2. Auxiliary Constructor:

    Here is a class Calculator with a primary constructor and an auxiliary constructor:

    scala
    class 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:

    scala
    val calculator1 = new Calculator() calculator1.add(5) val calculator2 = new Calculator(10) calculator2.add(7)

    Output:

    csharp
    Calculator 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:

  1. Simple Method:

    Let is define a class MathUtils with a simple method to add two numbers:

    scala
    class MathUtils { def add(a: Int, b: Int): Int = { a + b } }

    Using the method:

    scala
    val mathUtils = new MathUtils() val sum = mathUtils.add(3, 7)

    Output: sum will contain the value 10.

  2. Method with String Return:

    Create a class StringUtils with a method that concatenates two strings:

    scala
    class StringUtils { def concatenate(str1: String, str2: String): String = { str1 + " " + str2 } }

    Using the method:

    scala
    val 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 sum(a: Int, b: Int) = a + b

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

 Example:

Following example illustrates about Scala constructor and method

Save the file as −  ConstructorTest.scala. 

 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:

Output:

result 10

addResult 30



Search
Related Articles

Leave a Comment: