Total WebSite Views Count

Scala Spark & Flink

Features of Scala

There are following features of scala:
  • Type inference
  • Singleton object
  • Immutability
  • Lazy computation
  • Case classes and Pattern matching
  • Concurrency control
  • String interpolation
  • Higher order function
  • Traits
  • Rich collection set

Type Inference

In Scala, you don't require to mention data type and function return type explicitly. Scala is enough smart to deduce the type of data. The return type of function is determined by the type of last expression present in the function.

Singleton object

In Scala, there are no static variables or methods. Scala uses singleton object, which is essentially class with only one object in the source file. Singleton object is declared by using object instead of class keyword.

Immutability

Scala uses immutability concept. Each declared variable is immutable by default. Immutable means you can't modify its value. You can also create mutable variables which can be changed.
Immutable data helps to manage concurrency control which requires managing data.

Lazy Computation

In Scala, computation is lazy by default. Scala evaluates expressions only when they are required. You can declare a lazy variable by using lazy keyword. It is used to increase performance.

Case classes and Pattern matching

Scala case classes are just regular classes which are immutable by default and decomposable through pattern matching.
All the parameters listed in the case class are public and immutable by default.
Case classes support pattern matching. So, you can write more logical code.

Concurrency control

Scala provides standard library which includes the actor model. You can write concurrency code by using actor. Scala provides one more platform and tool to deal with concurrency known as Akka. Akka is a separate open source framework that provides actor-based concurrency. Akka actors may be distributed or combined with software transactional memory.

String Interpolation

Since Scala 2.10.0, Scala offers a new mechanism to create strings from your data. It is called string interpolation. String interpolation allows users to embed variable references directly in processed string literals. Scala provides three string interpolation methods: s, f and raw.

Higher Order Functions

Higher order function is a function that either takes a function as argument or returns a function. In other words, we can say a function which works with another function is called higher order function.
Higher order function allows you to create function composition, lambda function or anonymous function etc.

Traits

A trait is like an interface with a partial implementation. In Scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods.
Traits are compiled into Java interfaces with corresponding implementation classes that hold any methods implemented in the traits.

Rich Set of Collection

Scala provides rich set of collection library. It contains classes and traits to collect data. These collections can be mutable or immutable. You can use it according to your requirement. Scala.collection.mutable package contains all the mutable collections. You can add, remove and update data while using this package.
Scala.collection.immutable package contains all the immutable collections. It does not allow you to modify data.



Scala If-Else-If Ladder Statement

The scala if-else-if ladder executes one condition among the multiple conditional statements.

var number:Int =94 
if(number>=0 && number<50){  
    println ("fail")  
}  
else if(number>=50 && number<60){  
    println("D Grade")  
}  
else if(number>=60 && number<70){  
    println("C Grade")  
}  
else if(number>=70 && number<80){  
    println("B Grade")  
}  
else if(number>=80 && number<90){  
    println("A Grade")  
}  
else if(number>=90 && number<=100){  
    println("A+ Grade")  
}  
else println ("Invalid")  



Data Types in Scala

Data types in scala are much similar to java in terms of their storage, length, except that in scala there is no concept of primitive data types every type is an object and starts with capital letter. A table of data types is given below. You will see their uses further.

Data TypeDefault ValueSize
BooleanFalseTrue or false
Byte08 bit signed value (-27 to 27-1)
Short016 bit signed value(-215 to 215-1)
Char'\u0000'16 bit unsigned Unicode character(0 to 216-1)
Int032 bit signed value(-231 to 231-1)
Long0L64 bit signed value(-263 to 263-1)
Float0.0F32 bit IEEE 754 single-precision float
Double0.0D64 bit IEEE 754 double-precision float
StringNullA sequence of characters




Scala Pattern Matching

Underscore (_) is used in the last case for making it default case.

  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         var result = search ("Hello")  
  4.         print(result)  
  5.     }  
  6.     def search (a:Any):Any = a match{  
  7.         case 1  => println("One")  
  8.         case "Two" => println("Two")  
  9.         case "Hello" => println("Hello")  
  10.         case _ => println("No")  
  11.               
  12.         }  
  13. }  



Scala Infinite While Loop 

You can also create an infinite while loop. In the below program, we just passed true in while loop. Be careful, while using infinite loop.
  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.       var a = 10;           // Initialization  
  4.       whiletrue ){        // Condition  
  5.          println(a);  
  6.          a = a+20            // Incrementation  
  7.       }  
  8.    }  
  9. }  

Scala Case

Scala Case Classes and Case Object

Scala case classes are just regular classes which are immutable by default and decomposable through pattern matching.
It uses equal method to compare instance structurally. It does not use new keyword to instantiate object.
All the parameters listed in the case class are public and immutable by default.

Syntax
  1. case class className(parameters)  

Scala Case Class Example

  1. case class CaseClass(a:Int, b:Int)  
  2.   
  3. object MainObject{  
  4.     def main(args:Array[String]){  
  5.         var c =  CaseClass(10,10)       // Creating object of case class  
  6.         println("a = "+c.a)               // Accessing elements of case class  
  7.         println("b = "+c.b)  
  8.     }  
  9. }  

Scala Function Declaration

  1. def functionName(parameters : typeofparameters) : returntypeoffunction = {  
  2. // statements to be executed  
  3. }  

  1. object MainObject {  
  2.    def main(args: Array[String]) = {  
  3.         functionExample(10,20)   
  4.     }  
  5.     def functionExample(a:Int, b:Int) = {  
  6.           var c = a+b  
  7.           println(c)  
  8.     }  
  9. }  

Scala Recursion Function

In the program given below, we are multiplying two numbers by using recursive function.
In scala, you can create recursive functions also. Be careful while using recursive function. There must be a base condition to terminate program safely.

  1. object MainObject {  
  2.    def main(args: Array[String]) = {  
  3.         var result = functionExample(15,2)   
  4.         println(result)  
  5.     }  
  6.     def functionExample(a:Int, b:Int):Int = {  
  7.         if(b == 0)          // Base condition  
  8.          0  
  9.         else  
  10.          a+functionExample(a,b-1)  
  11.     }  
  12. }  



Scala Function Parameter example with default value

  1. object MainObject {  
  2.    def main(args: Array[String]) = {  
  3.         var result1 = functionExample(15,2)     // Calling with two values  
  4.         var result2 = functionExample(15)   // Calling with one value  
  5.         var result3 = functionExample()     // Calling without any value  
  6.         println(result1+"\n"+result2+"\n"+result3)  
  7.     }  
  8.     def functionExample(a:Int = 0, b:Int = 0):Int = {   // Parameters with default values as 0  
  9.         a+b  
  10.     }  
  11. }  


Scala For Loop


Scala for loop

In scala, for loop is known as for-comprehensions. It can be used to iterate, filter and return an iterated collection. The for-comprehension looks a bit like a for-loop in imperative languages, except that it constructs a list of the results of all iterations.
Syntax
  1. for( i <- range){  
  2.     // statements to be executed  
  3. }  
In the above syntax, range is a value which has start and end point. You can pass range by using to or until keyword.

Scala for-loop example by using to keyword

  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         for( a <- 1 to 10 ){  
  4.          println(a);  
  5.       }  
  6.    }  
  7. }  

In the below example, until is used instead of to. The major difference between until and to is, to includes start and end value given in the range, while until excludes last value of the range. So, the below example will print only 1 to 9.

Scala for-loop Example by using until keyword

  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         for( a <- 1 until 10 ){  
  4.          println(a);  
  5.       }  
  6.    }  
  7. }  
It is helpful to apply until keyword when you are iterating string or array, because array range is 0 to n-1. until does not exceed to n-1. So, your code will not complain of upper range.

Scala for-loop filtering Example

You can use for to filter your data. In the below example, we are filtering our data by passing a conditional expression. This program prints only even values in the given range.
  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         for( a <- 1 to 10 if a%2==0 ){  
  4.          println(a);  
  5.       }  
  6.    }  
  7. }  
Scala for-loop Example by using yield keyword
In the above example, we have used yield keyword which returns a result after completing of loop iterations. The for use buffer internally to store iterated result and after finishing all iterations it yields the final result from that buffer. It does not work like imperative loop.
  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         var result = for( a <- 1 to 10) yield a  
  4.         for(i<-result){  
  5.             println(i)  
  6.         }  
  7.    }  
  8. }  
Scala for-loop in Collection
In scala, you can iterate collections like list, sequence etc, either by using for each loop or for-comprehensions.
Let's see an example.

Scala for- loop Example for Iterating Collection

  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         var list = List(1,2,3,4,5,6,7,8,9)          // Creating a list  
  4.         for( i <- list){                         // Iterating the list  
  5.             println(i)  
  6.         }  
  7.           
  8.    }  
  9. }  
Scala for-each loop Example for Iterating Collection
In the below code we have use three approaches of for-each loop. You can implement any of them according to your need.
  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         var list = List(1,2,3,4,5,6,7,8,9)  // Creating a list  
  4.         list.foreach{  
  5.             println     // Print each element  
  6.         }  
  7.         list.foreach(print)  
  8.         println  
  9.         list.foreach((element:Int)=>print(element+" "))      // Explicitly mentioning type of elements  
  10.    }  
  11. }  
Scala for-loop Example using by keyword
In the above example, we have used by keyword. The by keyword is used to skip the iteration. When you code like: by 2 it means, this loop will skip all even iterations of loop.
  1. object MainObject {  
  2.    def main(args: Array[String]) {  
  3.         for(i<-1 to 10 by 2){  
  4.             println(i)  
  5.         }  
  6.    }  
  7. }  


Scala Higher Order Functions

Higher order function is a function that either takes a function as argument or returns a function. In other words we can say a function which works with function is called higher order function.
Higher order function allows you to create function composition, lambda function or anonymous function etc.
Let's see an example.

Scala Example: Passing a Function as Parameter in a Function

  1. object MainObject {  
  2.    def main(args: Array[String]) = {  
  3.      functionExample(25, multiplyBy2)                   // Passing a function as parameter  
  4.     }  
  5.     def functionExample(a:Int, f:Int=>AnyVal):Unit = {  
  6.         println(f(a))                                   // Calling that function   
  7.     }  
  8.     def multiplyBy2(a:Int):Int = {  
  9.         a*2  
  10.     }  
  11. }  

TechnicalArchitectBrain

AWS Services

AWS Services

Technology Selection & Evaluation Criteria

Technology Selection & Evaluation Criteria

Scale Cube - Scale In X Y Z Cube

Scale Cube - Scale In X Y Z Cube

Feature Post

AWS Services

About Me

About Me

Spring Cloud

Spring Cloud
Spring Cloud

Spring Cloud +mCloud Native + Big Data Archittect

Spring Cloud +mCloud Native + Big Data Archittect

ACID Transaction

ACID Transaction

Data Pipe Line Stack

Data Pipe Line Stack

Popular Posts