SCALA : Knowing #TOP10 Basics, why it is so functional
1) Type of Valriables
Variables are simply a storage location. Every variable is known by its name and stores some known and unknown piece of information known as value. So one can define a variable by its data type and name, a data type is responsible for allocating memory for the variable. In SCALA there are two types of variable:
- Mutable Variables
- Immutable Variables
val Variable_name: Data_type = "value"
package com.test.util
import scala.util.control.Breaks._
object BasicSample {
def main(args: Array[String]) {
var obj = new BasicClass();
obj.show()
obj.valueDemo()
obj.loopDemo()
}
}
class BasicClass {
var name = "test name"
var age = 10;
def show() {
println(" name " + name + " age " + age)
}
def valueDemo() {
var x: Int = 20;
var y: Int = 10;
var sum = x + y;
println("Display the result of + identifier:" + sum);
}
def loopDemo() {
var x: Int = 20;
var y: Int = 10;
if (x > 10) {
println(" x:" + x);
} else {
println("y :" + y)
}
while (y < 20) {
y = y + 1;
}
// Here, breakable is used to prevent exception
breakable {
for (i <- 1 to 10) {
if (i == 6)
// the value of i is equal to 6
break
else
println(i);
}
}
}
}
2) Class and Object
As shown in above example the class and object can be defined same as Java and any other programming language
3) Trait
It is similar to interface in Java and provides to define the behavior but not the implementation.
4) Diamond problem
Java had a issue with multiple interfaces and it is solved in Scala by using syntax pattern. In scala the right most parent is used to same implementation
5) Singleton Object
Be default in Scala, objects are Singleton. In above example object BasicSample is singleton.
6) Companion Object
Companion object is known as an object whose name is same as the name of the class. Or In other words, when an object and a class have the same name
7) Scala Constructors
Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.
Scala supports two types of constructors:
Primary Constructor
class Basic( name : String , age : Int){
}
Auxiliary Constructor
class Basic( name : String , age : Int){
var location : String ="Delhi";
def this (name : String , age : Int, location : String){
this(name, age)
this. location = location
}
}
Comments
Post a Comment