SCALA – INHERITANCE AND LOOPS

  • date 18th January, 2022 |
  • by Prwatech |
  • 0 Comments

SCALA – INHERITANCE AND LOOPS

 

Inheritance in Scala  

Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in Scala by which one class is allowed to inherit the features (fields and methods) of another class. 

Important terminology: 

  • Super Class: The class whose features are inherited is known as superclass (or a base class or a parent class). 
  • Sub Class: The class that inherits the other class is known as subclass (or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. 
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. 

 

How to use inheritance in Scala? 

The keyword used for inheritance is extends. 

Syntax: 

 

class parent_class_name extends child_class_name{ 

// Methods and fields 

}

 

 

Types of inheritance:  

There are 5 types of inheritance  

Single level inheritance:  

In single inheritance, derived class inherits the features of one base class. In the image below, class A serves as a base class for the derived class B. 

 

Multi-level inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to another class. In the below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. 

 

Hierarchical Inheritance:In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In below image, class A serves as a base class for the derived class B, C, and D. 

Multiple Inheritance: In Multiple inheritance, one class can have more than one superclass and inherit features from all parent classes. Scala does not support multiple inheritance with classes, but it can be achieve by traits. 

 

Note: Two classes, cannot be extended by one class at the same time. We can achieve this by the concept of trait.  

Trait:  By using Trait we can achieve inheritance. 

Trait is a super type of class. where it can be common behavior or it can be individual behavior. 

Hybrid Inheritance: It is a mix of two or more of the above types of inheritance. Since Scala doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In Scala, we can achieve hybrid inheritance only through traits. 

 

Nested if else: means one conditions has many conditions  

 

object Insurance { 
  def main(args: Array[String]) = { 
    val p_amt: Double = 9083.54 
    val age: Int = 44 
    if (age > 30) { 
      if (age > 40) { 
        println("Insurance Premium will be 3x of principal amt:" + 3 * (p_amt) + "INR") 
      } 
      else { 
        println("Insurance premium will be 1x of principal amt: " + p_amt) 
      } 
    } 
    else { 
      println("Insurance can not be given") 
    } 
  } 
}

 

Output: 

Insurance Premium will be 3x of principal amt:27250.620000000003INR 

 

 

object Insurance { 
  def main(args: Array[String]) = { 
    val p_amt: Double = 9083.54 
    val age: Int = 35 
    if (age > 30) { 
      if (age > 40) { 
        println("Insurance Premium will be 3x of principal amt:" + 3 * (p_amt) + "INR") 
      } 
      else { 
        println("Insurance premium will be 1x of principal amt: " + p_amt) 
      } 
    } 
    else { 
      println("Insurance can not be given") 
    } 
  } 
}

 

Output: 

Insurance premium will be 1x of principal amt: 9083.54 

 

 

object Insurance { 
  def main(args: Array[String]) = { 
    val p_amt: Double = 9083.54 
    val age: Int = 26 
    if (age > 30) { 
      if (age > 40) { 
        println("Insurance Premium will be 3x of principal amt:" + 3 * (p_amt) + "INR") 
      } 
      else { 
        println("Insurance premium will be 1x of principal amt: " + p_amt) 
      } 
    } 
    else { 
      println("Insurance can not be given") 
    } 
  } 
}

 

Output: 

Insurance can not be given 

Process finished with exit code 0 

If ladder statement: 

 

object Loan { 
  def main(args: Array[String]) = { 
    var roi:Double = 0.0 
    val cibil_score:Int=830 
    val loan_amount = 500000 
    if (cibil_score>700 && cibil_score<900) { 
      println("ROI, from HDFC would be:" + 8.25) 
      println("Monthly EMI would be:" +(500000)/(8.25*12)) 
    } 
    else if(cibil_score>800 && cibil_score<900) { 
        println("ROI,from HDFC would be :" + 7.9) 
      println("Monthly EMI would be:" +(500000)/(7.9*12)) 
    } 
      else { 
        println("Loan can not be approved , because required CIBIL SCORE is less" ) 
      } 
  } 
}

 

Output: 

ROI, from HDFC would be:8.25 

Monthly EMI would be:5050.50505050505 

 

 

object Loan { 
  def main(args: Array[String]) = { 
    var roi:Double = 0.0 
    val cibil_score:Int=830 
    val loan_amount = 500000 
    if (cibil_score>700 && cibil_score<800) { 
      println("ROI, from HDFC would be:" + 8.25) 
      println("Monthly EMI would be:" +(500000)/(8.25*12)) 
    } 
    else if(cibil_score>=800 && cibil_score<900) { 
        println("ROI,from HDFC would be :" + 7.9) 
      println("Monthly EMI would be:" +(500000)/(7.9*12)) 
    } 
      else { 
        println("Loan can not be approved , because required CIBIL SCORE is less" ) 
      } 
  } 
}

 

Output: 

ROI,from HDFC would be :7.9 

Monthly EMI would be:5274.261603375527 

 

 

object Loan { 
  def main(args: Array[String]) = { 
    var roi:Double = 0.0 
    val cibil_score:Int=680 
    val loan_amount = 500000 
    if (cibil_score>700 && cibil_score<800) { 
      println("ROI, from HDFC would be:" + 8.25) 
      println("Monthly EMI would be:" +(500000)/(8.25*12)) 
    } 
    else if(cibil_score>=800 && cibil_score<900) { 
        println("ROI,from HDFC would be :" + 7.9) 
      println("Monthly EMI would be:" +(500000)/(7.9*12)) 
    } 
      else { 
        println("Loan can not be approved , because required CIBIL SCORE is less" ) 
      } 
  } 
}

 

Output: 

Loan cannot be approved, because required CIBIL SCORE is less 

 

one element we can use: if, if else statement  

for multiple element we always work with for loop and while loop 

 

 

Loops (while, do. While, for, nested loops) 

Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Scala provides the different types of loop to handle the condition based situation in the program. The loops in Scala are: 

while Loop 

A while loop generally takes a condition in parenthesis. If the condition is True, then the code within the body of the while loop is executed. A while loop is used when we don’t know the number of times we want the loop to be executed however we know the termination condition of the loop. It is also known as an entry controlled loop as the condition is checked before executing the loop. The while loop can be thought of as a repeating if statement.
Syntax: 

while (condition) 

{ 

    // Code to be executed 

}

 

While loop starts with the checking of the condition. When the condition becomes false, the loop terminates which marks the end of its life cycle. 

 Infinite While Loop: While loop can execute infinite times which means there is no terminating condition for this loop. In other words, we can say there are some conditions which always remain true, which causes while loop to execute infinite times or we can say it never terminates.
Example: Below program will print the specified statement infinite time and also give the runtime error Killed (SIGKILL) on online IDE.
 

Do…while Loop 

A do..while loop is almost same as a while loop. The only difference is that do..while loop runs at least one time. The condition is checked after the first execution. A do..while loop is used when we want the loop to run at least one time. It is also known as the exit controlled loop as the condition is checked after executing the loop.
Syntax:
 

 

do { 

 

// statements to be Executed 

 

} while(condition);

 

for Loop 

for loop has similar functionality as while loop but with different syntax. for loops are preferred when the number of times loop statements are to be executed is known beforehand. There are many variations of “for loop in Scala” which we will discuss in upcoming articles. Basically, it is a repetition control structure which allows the programmer to write a loop that needs to execute a particular number of times. 

Nested Loops 

 It can contain the for loop inside a for loop or a while loop inside a while loop. It is also possible that a while loop can contain the for loop and vice-versa. 

For loop: with the help of for loop we can deal with multiple statements. 

Question: what are the difference between for loop and while loop? 

For loop: Iteration is known. 

For loop we use when we know the number of iteration. When iteration is knowing how many times we are going to run loop. 

Example of for loop. 

 

object Iter_Marks { 
  def main(args:Array[String])={ 
    for(i <-1 to 10){ 
      println("Element : " +i) 
    } 
  } 
}

 

 

Process finished with exit code 0 

Question: Write a program to print step values given in range? 

Program: Suppose i =1,2,3,4,5,6,7,8,9,10 

by 2 means it will work as step size. Firstly, it will print 1 then skip next value then print 3 and then 5,7,9 

output will be: 1,3,5,7,9 

 

object Iter_Marks { 
  def main(args:Array[String])={ 
    for(i <-1 to 10 by 2){ 
      println("Element : " +i) 
    } 
  } 
}

 

 

 

Process finished with exit code 0  

By 4: it wll work as step size 4 

 

object Iter_Marks { 
  def main(args:Array[String])={ 
    for(i <-1 to 10 by 4){ 
      println("Element : " +i) 
    } 
  } 
}

 

Element : 1 

#Element : 5 

Element : 9 

 

Process finished with exit code 0 

 

object Iter_Marks { 
  def main(args:Array[String])={ 
    for(i <- 1 to 10) { 
      if(i%2!=0) 
        println("Odd Element :" + (i)) 
    } 
  } 
  }

 

 

 

 

 

object Iter_Marks { 
  def main(args:Array[String])={ 
    for(i <- 1 to 10) { 
      if(i%2==0) 
        println("Even Element :" + (i)) 
    } 
  } 
  }

 

 

 

Question: Can we use filter operation within for loop? 

 

object Iter_Marks { 
  def main(args:Array[String])= { 
    val res= for(i <-1 to 10) yield(i) 
    println(res) 
  } 
  } 

 

Output “ 

Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 

Process finished with exit code 0 

How to print this output in separate line?  

 

object Iter_Marks { 
  def main(args:Array[String])= { 
    val res= for(i <-1 to 10) yield(i) 
    for(j <-res) 
    println(j) 
  } 
  }

 

 

1 

2 

3 

4 

5 

6 

7 

8 

9 

10 

Process finished with exit code 0 

yield(i): means println is not actually storing anything any output in any variable. println is just printing that output in the console. 

Converting assembly language to binary language (0,1). 

 

object Iter_Marks { 
  def main(args:Array[String])= { 
    val res= for(i <-1 to 10) yield(i) 
    for(j <-res){ 
      if (j==3) 
      println("Third Element : " +j) 
    } 
  } 
  } 

 

Output: 

Third Element : 3 

Process finished with exit code 0 

we can take collection elements List and iterate using for loop  

 

object Iter_Marks { 
  def main(args: Array[String]) = { 
    val l = List(1,2,3,4,5) 
    for(x <-l) { 
        println(x) 
    } 
  } 
}

 

 

Output : 

1 

2 

3 

4 

5 

 

Process finished with exit code 0 

 

While loop: Iteration is unknown. 

 while loop is use when we are unknown to iteration. We do not use how many times we have to iterate 

 

object Iter_Num { 
  def main(args: Array[String]) = { 
    val num:Int = 10 
    var ind:Int = 0 
    while(ind<num) { 
      println("Element : " +ind) 
      ind += 1 
    } 
  } 
 
}

 

Process finished with exit code 0 

Infinite while loop : 

If we donot include boundary condition then the loop will  go on the infinite .For example in the previous program ind += 1 it is a boundary condition  

 

object Iter_Num { 
  def main(args: Array[String]) = { 
    val num: Int = 10 
    var ind: Int = 0 
    while (ind < num) { 
      println("Element : " + ind) 
      // ind += 2 
    } 
  } 
}

 

 

. 

. 

. 

. 

. 

. 

Element : 0 

Do while loop:  

 

object Iter_Num { 
  def main(args: Array[String]) = { 
    val num:Int = 10 
    var ind:Int = 0 
    do { 
      println("Element : " +ind) 
      ind += 2 
    } 
    while(ind<num) 
  } 
}

 

Element : 0 

#Element : 2 

Element : 4 

#Element : 6 

Element : 8 

 

Pattern matching  

in pattern mathing will be using case classes will be 

 

object Pat_match { 
  def main(args: Array[String]) = { 
 
    val x: Int = 10 
    x match { 
      case 10 => println("Found") 
      case 11 => println("Not found") 
      case _ => println("It's not int") 
    } 
 
  } 
}

 

Output:  

Found 

 

 

object Pat_match { 
  def main(args: Array[String]) = { 
 
    val x: Int = 100 
    x match { 
      case 10 => println("Found") 
      case 11 => println("Not found") 
      case _ => println("It's not int") 
    } 
 
  } 
}

 

Output: 

It’s not int 

 

 

 

object Pat_match { 
  def main(args: Array[String]) = { 
    val res = check("Hello") 
  } 
  def check(a:Any):Any = a match { 
    case "Hello" => println("String is found") 
    case "hello" => println("String is not found") 
    case _ => println("Data type def is missing") 
  } 
  }

 

Output:   SCALA – INHERITANCE AND LOOPS

String is found 

 

 

object Pat_match {
  def main(args: Array[String]) = {
    val res = check("Hello")
  }
  def check(a:Any) = a match {
    case "Hello" => println("String is found")
    case "hello" => println("String is not found")
    case _ => println("Data type def is missing")
  }
  }

 

Output: SCALA – INHERITANCE AND LOOPS

String is found 

 

 

object Pat_match {
  def main(args: Array[String]) = {
    val res = check("HELLO")
  }
  def check(a:Any) = a match {
    case "Hello" => println("String is found")
    case "hello" => println("String is not found")
    case _ => println("Data type def is missing")
  }
  }

 

 

Output: 

Data type def is missing 

 

object Pat_match {
  def main(args: Array[String]) = {
    val res = check("hello")
  }
  def check(a:Any) = a match {
    case "Hello" => println("String is found")
    case "hello" => println("String is not found")
    case _ => println("Data type def is missing")
  }
  }

 

Output: 

String is not found 

 

Single level inheritance 

Protected can provide access is for subclasses but other packages can not exist 

 

class Single_Lev {
  val prop:Double = 3000.00
  protected var are_house:Double = 2000.00
  def house () = {
    println("Villa is built over" + are_house +"sq ft.")
  }
}
class Child_A extends Single_Lev {
  def child_house() = {
  println("child house is built in area of" + (prop - are_house) + "sq ft.")
}
}
object SCA {
  def main(args:Array[String]) ={
    val c = new Child_A()
    c.child_house()
    c.house()
    println("Single inheritance implemented")
  }
}

 

 

Output: 

child house is built in area of1000.0sq ft. 

Villa is built over2000.0sq ft. 

Single inheritance implemented 

SCALA – INHERITANCE AND LOOPS

 

0
0

Quick Support

image image