Features of Scala
Type InferenceIn 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 objectIn 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.ImmutabilityScala 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 ComputationIn 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 matchingScala 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 controlScala 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 InterpolationSince 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 FunctionsHigher 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. TraitsA 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 CollectionScala 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")
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 Type | Default Value | Size |
---|---|---|
Boolean | False | True or false |
Byte | 0 | 8 bit signed value (-27 to 27-1) |
Short | 0 | 16 bit signed value(-215 to 215-1) |
Char | '\u0000' | 16 bit unsigned Unicode character(0 to 216-1) |
Int | 0 | 32 bit signed value(-231 to 231-1) |
Long | 0L | 64 bit signed value(-263 to 263-1) |
Float | 0.0F | 32 bit IEEE 754 single-precision float |
Double | 0.0D | 64 bit IEEE 754 double-precision float |
String | Null | A sequence of characters |
Scala Pattern Matching
Underscore (_) is used in the last case for making it default case.
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.
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
Scala Case Class Example
Scala Function Declaration
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.
Scala Function Parameter example with default value
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
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
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
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.
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.
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
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.
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.
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.