Sunday, April 9, 2017

Scala

Few Points

1. What is Mutable and Immutable?
If the values in the object anc be changed then it is called Mutable and in immutable objects values cannot be modified.

2. What is Scala map?

Scala map is a collection of Key Value pairs where Keys are unique and Values are not Unique. Scala supports two kinds of maps- mutable and immutable. By default, Scala supports immutable map and to make use of the mutable map, programmers have to import the scala.collection.mutable.Map class explicitly. When programmers want to use mutable and immutable map together in the same program then the mutable map can be accessed as mutable.map and the immutable map can just be accessed with the name of the map.

3. Scala Singleton and Companion Objects

Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object.

A singleton object is declared using the object keyword. Here is an example:

object Main {
    def sayHi() {
        println("Hi!");
    }
}
This example defines a singleton object called Main. You can call the method sayHi() like this:

Main.sayHi();
Notice how you write the full name of the object before the method name. No object is instantiated. It is like calling a static method in Java, except you are calling the method on a singleton object instead.

Companion Objects
When a singleton object is named the same as a class, it is called a companion object. A companion object must be defined inside the same source file as the class. Here is an example:

class Main {
    def sayHelloWorld() {
        println("Hello World");
    }
}

object Main {
    def sayHi() {
        println("Hi!");
    }
}
In this class you can both instantiate Main and call sayHelloWorld() or call the sayHi() method on the companion object directly, like this:

var aMain : Main = new Main();
aMain.sayHelloWorld();

Main.sayHi();

Singleton object: created using object keyword. No static classes, so use singleton objects.
Companion Object: Consider a class already exists. Now created object with the same name as of class.
Difference is a class with same name as of Singleton class does not exist. If exists, it becomes companion object.

What Companion Object can Do?
It can access private variables of the class to which it is linked.

Usecase of Companion Object: Case Class

On Invoking companion object(or Creating object of Companion object) it will call the apply method of the companion object. This apply() will have initialization functionality of class variables.
When a case class is created 2 things are created A class + companion object.

Eg:

case class A(id: int,name: String)       //A Class + companion Object A are created

val objA = new A(1,"Leela")         //apply() of case class gets called that can access private variables id and name and initializes with the input values.

In a class, to access private variables Get and Set methods are to be implemented.But we don't want to access member variables using get and set functions. In this case companion object comes into picture which can directly access class member variables.


5) What do you understand by “Unit” and “()” in Scala?

Scala equivalent of Java void. Empty tuple i.e. () in Scala is a term that represents unit value. Used while returning from function.

If there is no = symbolbetween method declaration and definition, then scala runtime assign Unit(void) as return type.

Eg:
scala> def isPalindrome(str: String)
     | {
     | if(str == str.reverse)
     |      println("This string is palindrome:" + str)
     | else
     |      println("THis is not")
     | }
isPalindrome: (str: String)Unit

6) Differentiate between Val and var in Scala.

Val refers to immutable declaration of a variable whereas var refers to mutable declaration of a variable in Scala.

7) What is a trait?

A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits.

Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters.

A trait definition looks just like a class definition except that it uses the keyword trait. The following is the basic example syntax of trait. So a trait is very similar to what we have abstract classes in Java.

Syntax
trait Equal {
   def isEqual(x: Any): Boolean
   def isNotEqual(x: Any): Boolean = !isEqual(x)
}

class Point(xc: Int, yc: Int) extends Equal {
   var x: Int = xc
   var y: Int = yc
   
   def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == y
}

object Demo {
   def main(args: Array[String]) {
      val p1 = new Point(2, 3)
      val p2 = new Point(2, 4)
      val p3 = new Point(3, 3)

      println(p1.isNotEqual(p2))
      println(p1.isNotEqual(p3))
      println(p1.isNotEqual(2))
   }
}

8) What is Monad?

The simplest way to define a monad is to relate it to a wrapper. Just like you wrap any gift or present into a shiny wrapper with ribbons to make them look attractive. 

provide two important operations –



Identity through “unit” in Scala

Bind through “flatMap” in Scala

No comments:

Post a Comment