Pages

Showing posts with label scala. Show all posts
Showing posts with label scala. Show all posts

Thursday, 31 March 2022

Scala Exception Handling ( Try catch & try finally )

  

Try-Catch construct in Java and Scala have some differences :


In Java : 
Try-Catch expression results in value and for each exception, we need a sperate catch block.

In Scala : 
Try-Catch construct results in exception which can pattern matched and don't need separate catch block for each exception, under same catch block using case statement, we can have multiple exceptions with each implemented with next execution steps. 

try catch :

Syntax :
try {
  //-- Code to Run 
  //-- Code to Run
}
catch {
  case f:java.io.FileNotFoundException => { //-- code }
  case n:NullPointerException => { //-- code }
  case e:Exception => { //-- code }
} 

 

 try finally :

Syntax :
try {
  //-- Code to Run 
  //-- Code to Run
} finally {
     //-- code will always execute
     //-- with or without exception occurred
}
 

 Examples of scala Exceptions:

ArrayIndexOutOfBoundsException
ArithmeticException
java.lang.Exception
NumberFormatException


Interview Questions on scala Exceptions:

How do you check for exceptions in Scala? < use catch >
How to raise an arithmetic exception in Scala? < throw exception >
Why try/catch in Scala is an expression?




keywords : 
how to handle exceptions in scala,try catch in scala, scala exceptions, best way to handle exceptions, exception handling scala interview questions, scala tutorial, scala vs python.
sample exceptions :
java.io.FileNotFoundException: (No such file or directory)
Exception in thread "main" java.lang.NoSuchMethodError: scala.collection.mutable.Buffer$.empty()Lscala/collection/GenTraversable;

Wednesday, 30 March 2022

Scala Loops ( For loop, while loop and do While loop )

 

For Loop :

Syntax :
for (condition) {
  //-- Code to Run 
  //-- Code to Run
}
 
Rule :
1. Check condition
2. If condition is True then run code withing for loop else exit 
 
Example:
scala> val hadoopguru = Range(1, 10)
hadoopguru: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
 
scala> for (h <- hadoopguru) {
     |     println(s"Item : ${h}")
     | }
Item : 1
Item : 2
Item : 3
Item : 4
Item : 5
Item : 6
Item : 7
Item : 8
Item : 9


While Loop :

Syntax :
while (condition) {
  //-- Code to Run 
  //-- Code to Run
}
 
Rule :
1. Check condition
2. If condition is True then run code within while loop else if condition is False then exit 
 
Example: 
scala> var h = 0
h: Int = 0

scala> while (h < 10) {
     |   h = h+1
     |   println(s"Item : ${h}")
     | }
Item : 1
Item : 2
Item : 3
Item : 4
Item : 5
Item : 6
Item : 7
Item : 8
Item : 9
Item : 10

Note : While loop continue to run until condition is True. Be careful not to get into infinite loop.


do while Loop :

Syntax :
do {
     //-- Code to Run 
     //-- Code to Run
} while (condition);
 
Rule :
1. Run code at least once then Check condition
2. If condition is True then run code within while loop again else if condition is False then exit 
 
Example: 
scala> var h = 0
h: Int = 0

scala> do {
     |      h = h+1
     |      println(s"Item : ${h}")
     | } while (h < 0);
Item : 1

Note : do While loop is similar to while loop except code block runs at least once.






keywords : loops in scala, for loop, while loop, do while loop, scala interview questions, scala tutorial, scala vs python, learn scala, infinite loop.

Monday, 28 March 2022

Scala IF expression ( All Possible ways to use IF condition )


IF expression in single line :

if (expression) println("something")

Example: 
scala> if ("print" == "print") print("True")
True
 
OR
scala> if ("print" == "print") { print("True") }
True 


IF expression in multiple lines (multiline statement)

if (expression) {
       println("something1")
       println("something1")
   }
 
Example: 
scala> if ("print" == "print") {
     | println("True")
     | println("True")
     | }
True
True 


Assign value to variable using IF condition (expression)

Example: 

scala> val day = 1

day: Int = 1

scala> val curr_day = if (day == 1) { "Monday" } else {"Not A Monday"}

curr_day: String = Monday



Difference between Scala Array, List, Tuple and Range


Scala Array

Collection Object of same data type

Update Element : Yes (Reassignment is allowed) - MUTABLE object

Examples :

Array (Define & assign values to each Array element)

scala> var cities = Array("NewYork", "London", "Paris", "Mumbai")
cities: Array[String] = Array(NewYork, London, Paris, Mumbai)

Update Array Element with new value 

scala> cities(1) = "Toronto"
scala> cities
res12: Array[String] = Array(NewYork, Toronto, Paris, Mumbai)

Create Empty Array

scala> var cities = new Array[String](5)
cities: Array[String] = Array(null, null, null, null, null)


Scala List

Collection Object of same data type

Update Element : No (Reassignment is NOT allowed) - IMMUTABLE object

Examples :

Array (Define & assign values to each Array element)

scala> var cities = List("NewYork", "London", "Paris", "Mumbai")
cities: List[String] = List(NewYork, London, Paris, Mumbai)

Update Array Element with new value 

scala> cities(1) = "Toronto"
<console>:13: error: value update is not a member of List[String]
       cities(1) = "Toronto" 

Create Empty List ( Use Nil )

scala> var cities = Nil
cities: scala.collection.immutable.Nil.type = List()

 

Scala Tuple

Ordered Container of same or different data type 

Elements to be defined >= 2.

Update Element : Cannot be defined as collection of element - IMMUTABLE object

Examples :

Declare/create Tuple

scala> val hadoopguru = ("Hadoop", "Guru", 2022, 99.99)
hadoopguru: (String, String, Int, Double) = (Hadoop,Guru,2022,99.99)


Scala Range

Range can be defined with start & end value (optional stepping value). We can also exclude end value with different syntax.

Update Element : Yes (Reassignment is NOT allowed) - IMMUTABLE object

Examples :

Range (Include end value)

scala> 1 to 10
res2: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Range (Exclude end value)

scala> 1 until 10
res2: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

Range (Include start & end with stepping value)

scala> 1 to 22 by 3
res4: scala.collection.immutable.Range = Range(1, 4, 7, 10, 13, 16, 19, 22) 

Range (Include start & exclude end with stepping value)

scala> 1 to 22 by 3
res4: scala.collection.immutable.Range = Range(1, 4, 7, 10, 13, 16, 19)



Keywords : scala interview questions, top 50, top 10, data engineer, collection object, loop.