Intermediate Scala Interview Questions and Answers

1. What is Primary Constructor? What is Secondary or Auxiliary Constructor in Scala? What is the purpose of Auxiliary Constructor in Scala? Is it possible to overload constructors in Scala?

Scala has two kinds of constructors:

  • Primary Constructor
  • Auxiliary Constructor

Primary Constructor
In Scala, Primary Constructor is a constructor which is defined with class definition itself. Each class must have one Primary Constructor: Either Parameter constructor or Parameterless constructor.

Example:-

class Person

Above Person class has one Zero-parameter or No-Parameter or Parameterless Primary constructor to create instances of this class.

class Person (firstName: String, lastName: String)

Above Person class has a two Parameters Primary constructor to create instances of this class.

Auxiliary Constructor
Auxiliary Constructor is also known as Secondary Constructor. We can declare a Secondary Constructor using ‘def’ and ‘this’ keywords as shown below:

class Person (firstName: String, middleName:String, lastName: String){
  def this(firstName: String, lastName: String){
      this(firstName, "", lastName)
  }
}

2. What is the use of Auxiliary Constructors in Scala?Please explain the rules to follow in defining Auxiliary Constructors in Scala?

In Scala, The main purpose of Auxiliary Constructors is to overload constructors. Like Java, We can provide various kinds of constructors so that user can choose the right one based on his requirement.

Auxiliary Constructor Rules:

  • They are like methods only. Like methods, we should use ‘def’ keyword to define them.
  • We should use same name ‘this’ for all Auxiliary Constructors.
  • Each Auxiliary Constructor should start with a call to previous defined another Auxiliary Constructor or Primary Constructor. Otherwise compile-time error.
  • Each Auxiliary Constructor should differ with their parameters list: may be by number or types.
  • Auxiliary Constructors cannot call a super class constructors. They should call them through Primary Constructor only.
  • All Auxiliary Constructors call their Primary Constructor either directly or indirectly through other Auxiliary Constructors.

3. What are the major differences between Scala’s Auxiliary constructors and Java’s constructors?

Scala’s Auxiliary constructor is almost similar to Java’s constructor with few differences.

Compared to Java’s constructors, Auxiliary constructors have the following few differences:

  • The auxiliary constructors are called using “this” keyword.
  • All auxiliary constructor are defined with the same name that is “this”. In Java, we use class name to define constructors.
  • Each auxiliary constructor must start with a call to a previously defined auxiliary constructor or the primary constructor.
  • We use ‘def’ keyword to define auxiliary constructors like method/function definition. In Java, constructor definition and Method definition is different.

4. What are the differences between Array and ArrayBuffer in Scala?

Differences between Array and ArrayBuffer in Scala:

  • Array is fixed size array. We cannot change its size once its created.
  • ArrayBuffer is variable size array. It can increase or decrease it’s size dynamically.
  • Array is something similar to Java’s primitive arrays.
  • ArrayBuffer is something similar to Java’s ArrayList.

5. What is case class? What is normal class? Diff between the two?

  • Case class is a class which is defined with “case class” keywords. Because of this “case” keyword, we will get some benefits to avoid boilerplate code.
  • We can create case class objects without using “new” keyword, while normal class object cannot be created without new keyword.
case class Employee (name:String, val age:Int, var phone:String)
class Address(city: String)
object Main 
{ 
	// Main method 
	def main(args: Array[String]) 
	{ 
		var c = Employee("Harshit", 25, "123") 
                var d = new Address("Mumbai")
		
		// Display both Parameter 
		println("Name of the employee is " + c.name); 
		println("Age of the employee is " + c.age); 
		println("Address of the employee is " + d.city); 
	} 
} 

Output:
Name of the employee is Harshit
Age of the employee is 25
Address of the employee is Mumbai
  • By default, Scala compiler prefixes “val” for all constructor parameters.
c.name = "Jain" // ==> Not Allowed because default type is val

Output:
error: reassignment to val
        c.name = "Jain";

c.phone = "987" // ==> Allowed, because phone is of type var

  • Case class are serialized by default while Normal class are not serialized by default.
  • Case class have copy method to create a duplicate of the same object with changing some parameters or without altering them.

Advantages of case class:

  • We can use case classes in Pattern Matching.
  • By default, Case class and Case Objects are Serializable.
  • default implementations of equals and hashCode
  • a prettier default implementation of toString, and
  • the small amount of functionality that they get from automatically inheriting from scala.Product.
  • By default, Scala Compiler adds companion object with apply and unapply methods that’s why we don’t need new keyword to create instances of a case class.
  • By default, Scala Compiler adds copy method too for case class.

6. What is the difference between Case Object and Object(Normal Object)?

  • Normal object is created using “object” keyword. By default, It’s a singleton object.
object MyNormalObject
  • Case Object is created using “case object” keywords.By default, It’s also a singleton object.
case object MyCaseObject
  • By Default, Case Object is Serializable. But normal object is not.
  • Case Object has better default implementation of toString method.

7. What is the usage of isInstanceOf and asInstanceOf methods in Scala? Is there anything similar concept available in Java?

Both isInstanceOf and asInstanceOf methods are defined in Any class. So no need import to get these methods into any class or object.

“isInstanceOf” method is used to test whether the object is of a given type or not. If so, it returns true. Otherwise returns false.

   scala> val str = "Hello"
   scala>str.isInstanceOf[String]
   res0: Boolean = false   
 

“asInstanceOf” method is used to cast the object to the given a type. If the given object and type are of same type, then it cast to given type. Otherwise, it throws java.lang.ClassCastException.

scala> val str = "Hello".asInstanceOf[String]
str: String = Hello

scala> val str = 123.asInstanceOf[String]
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

8. Difference between Array and List in Scala?

  • Arrays are always Mutable where as List is always Immutable.
  • Once created, We can change Array values where as we cannot change List Object.
  • Arrays are fixed-size data structures where as List is variable-sized data structures. List’s size is automatically increased or decreased based on it’s operations we perform on it.
  • Arrays are Invariants where as Lists are Covariants.
val arr = Array(1,2,3)
arr(0) // ==> 1
arr(0) = 4
arr(0) // ==> 4

val list = List(1,2,3)
list(0) // ==> 1
list(0) = 4 // ==> Error : Not Allowed

val list2 = 4::list
list2 // ==> 4,1,2,3
list // ==> 1,2,3

val arr2 = 4::arr // ==> Error : Not Allowed

// Arrays are Invariant
val array: Array[Any] = Array[Int](1,2,3) // ==> Not Allowed.
scala> val arr:Array[Any] = Array[Int](1,2,3)
<console>:11: error: type mismatch;
 found   : Array[Int]
 required: Array[Any]
Note: Int <: Any, but class Array is invariant in type T.

// List are Covariant
val list: List[Any] = List[Int](1,2,3) // ==> Allowed.
scala> val list:List[Any] = List[Int](1,2,3)
list: List[Any] = List(1, 2, 3)

9. What is the difference between “val” and “lazy val” in Scala? What is Eager Evaluation? What is Lazy Evaluation?

“val” means value or constant which is used to define Immutable variables.

There are two kinds of program evaluations:

  • Eager Evaluation
  • Lazy Evaluation

Eager Evaluation means evaluating program at compile-time or program deployment-time irrespective of clients are using that program or not.

Lazy Evaluation means evaluating program at run-time on-demand that means when clients access the program then only its evaluated.

The difference between “val” and “lazy val” is that “val” is used to define variables which are evaluated eagerly and “lazy val” is also used to define variables but they are evaluated lazily.

10. What is the Relationship between equals method and == in Scala? Differentiate Scala’s == and Java’s == Operator?

In Scala, we do NOT need to call equals() method to compare two instances or objects. When we compare two instances with ==, Scala calls that object’s equals() method automatically.

Java’s == operator is used to check References Equality that is whether two references are pointing to the same object or not. Scala’s == is used to check Instances Equality that is whether two instances are equal or not.

11. Difference between Scala’s Inner class and Java’s Inner class?

In Java, Inner class is associated with Outer class that is Inner class a member of the Outer class.
Unlike Java, Scala treats the relationship between Outer class and Inner class differently. Scala’s Inner class is associated with Outer class object.

// Outer class 
class Geek 
{ 	
	// Inner class 
	class G1
	{ 
		var a = 0
		def method() 
		{ 
			for(a<-0 to 3) 
			{ 
				println("Welcome to inner class: G1"); 
			} 
		} 
	} 
} 
object Main 
{ 
	def main(args: Array[String]) 
	{ 		
		// Creating object of the outer and 
		// inner class Here, G1 class is 
		// bounded with the object of Geek class 
		val obj = new Geek(); 
		val o = new obj.G1; 
		o.method(); 
	} 
} 
Output:
Welcome to inner class: G1
Welcome to inner class: G1
Welcome to inner class: G1
Welcome to inner class: G1 

Explanation: In the above example, Geek is outer class and G1 is the inner class. Now, to create the object of the inner class, first of all, you need to create the object of the outer class and the object of the outer class is obj. Now, obj is prefixed with G1 class and create the object o of G1 class because the inner class is bound to the object of the outer class.

12. How to create class inside object and object inside class in Scala?

In Scala, we can also include a class inside an object or an object inside a class. Let’s discuss with an example. In the below example, first, we create an object inside a class and access the method of the object with the help of new keyword followed by the class name, object name and method name like as shown in the following statement:

new outer_class().inner_object.method;

Now, second, we create a class inside an object and access the methods present in the class accessed with the help of new keyword followed by the object name, class name and method name, as shown in the following statement:

new outer_object.inner_class().method; 
// Outer Class and inner Object 
class outer_class 
{ 
	object inner_object 
	{ 
		val q = 0; 
		def method() 
		{ 
			for(q <- 0 to 2) 
			{ 
				println("object inside a class example") 
			} 
			println() 
		} 
	} 
} 

// Outer Object inner Class 
object outer_object 
{ 
	class inner_class 
	{ 
		val s = 0; 
		def method() 
		{ 
			for(s <- 0 to 2) 
			{ 
				println("class inside an object example") 
			} 
		} 
	} 
} 

object Main 
{ 	
	// Main method 
	def main(args: Array[String]) 
	{ 		
		// Object inside a class 
		new outer_class().inner_object.method; 
		
		// Class inside an object 
		new outer_object.inner_class().method; 
	} 
} 
Output:
object inside a class example.
object inside a class example.
object inside a class example.

class inside an object example.
class inside an object example.
class inside an object example.

13. What is Diamond Problem? How Scala solves Diamond Problem?

A Diamond Problem is a Multiple Inheritance problem. Some people calls this problem as Deadly Diamond Problem.

In Scala, it occurs when a Class extends more than one Traits which have same method definition as shown below.

Unlike Java 8, Scala solves this diamond problem automatically by following some rules defined in Language. Those rules are called “Class Linearization”.

Example:-

trait A{   
  def display(){ println("From A.display")  }
}

trait B extends A{ 
  override def display() { println("From B.display") }
}

trait C extends A{ 
  override def display() { println("From C.display") }
}

class D extends B with C{ }

object ScalaDiamonProblemTest extends App {
    val d = new D
    d.display // ==> From C.display
}

Here output is “From C.display” form trait C. Scala Compiler reads “extends B with C” from right to left and takes “display” method definition from lest most trait that is C.

14. Why Scala does NOT have “static” keyword? What is the main reason for this decision?

As we know, Scala does NOT have “static” keyword at all. This is the design decision done by Scala Team.

The main reason to take this decision is to make Scala as a Pure Object-Oriented Language. “static” keyword means that we can access that class members without creating an object or without using an object. This is completely against with OOP principles.

If a Language supports “static” keyword, then that Language is not a Pure Object-Oriented Language. For instance, as Java supports “static” keyword, it is NOT a Pure Object-Oriented Language. But Scala is a Pure Object-Oriented Language.

15. What is the use of “object” keyword in Scala? How to create Singleton objects in Scala?

In Scala, object keyword is used the following purposes:

  • It is used to create singleton object in Scala.
object MySingletonObject

Here, MySingletonObject becomes singleton object automatically.

  • object keyword is used to define Scala Applications that is executable Scala programs.
object MyScalaExecutableProgram{   
   def main(args: Array[String]){
       println("Hello World")
   }
}

When we define main method in object as shown above (its same as main() method in Java), it becomes automatically as a executable Scala program.

  • It is used to define static members like static variables and static methods without using ‘static’ keyword.
object MyScalaStaticMembers{ 
  val PI: Double = 3.1414  
  def add(a: Int, b: Int) = a + b
}

By default PI variable and add methods will become as static members. That means we can call them without creating a separate object like MyScalaStaticMembers.add(10,20).

  • It is used to define Factory methods

16. How to define Factory methods using object keyword in Scala? What is the use of defining Factory methods in object?

In Scala, we use ‘object’ keyword to define Factory methods. The main purpose of these Factory methods in Scala is to avoid using ‘new’ keyword. Without using ‘new’ keyword we can create objects.

To define Factory methods:
We can use apply method to define Factory methods in Scala. If we have Primary Constructor and Multiple Auxiliary constructors, then we need to define multiple apply methods as shown below.

class Person(val firstName: String, val middleName: String, val lastName: String){
  def this(firstName: String, lastName: String){
    this(firstName,"",lastName)
  }
}
object Person{
  def apply(firstName: String, middleName: String, lastName: String) 
        = new Person(firstName,middleName,lastName)

  def apply(firstName: String, lastName: String) 
        = new Person(firstName, lastName)
}

Now we can create Person objects without using new keyword or with new keyword upto your wish.

val p1 = new Person("Scala","Java")
or 
val p1 = Person("Scala","Java")
class Person(val firstName: String, val middleName: String, val lastName: String) {
  def this(firstName: String, lastName: String) {
    this(firstName, "", lastName)
  }
}
object Person {
  def apply(firstName: String, middleName: String, lastName: String) = new Person(firstName, middleName, lastName)

  def apply(firstName: String, lastName: String) = new Person(firstName, lastName);

  def main(args: Array[String]): Unit = {
    val p = Person("h", "j")
    println(p)

    val pp = new Person("h", "j")
    println(pp)

    val ppp = Person("h", "s", "j")
    println(ppp)

    val pppp = new Person("h", "s", "j")
    println(pppp)
  }
}
Output:
Person@7d4991ad
Person@28d93b30
Person@1b6d3586
Person@4554617c

17. What is apply method in Scala? What is unapply method in Scala? What is the difference between apply and unapply methods in Scala?

In Scala, apply and unapply methods play very important role. They are also very useful in Play Framework in mapping and unmapping data between Form data and Model data.

In simple words,

  • apply method: To compose or assemble an object from it’s components.
  • unapply method: To decompose or dis-assemble an object into it’s components.

Scala’s apply method:
It is used to compose an object by using its components. Suppose if we want to create a Person object, then use firstName and laststName two components and compose Person object as shown below.

class Person(val firstName: String, val lastName: String)

object Person{
  def apply(firstName: String, lastName: String) 
        = new Person(firstName, lastName)
}

Scala’s unapply method:
It is used to decompose an object into its components. It follows reverse process of apply method. Suppose if we have a Person object, then we can decompose this object into it’s two components: firstName and laststName as shown below.

class Person(val firstName: String, val lastName: String)

object Person{
  def apply(firstName: String, lastName: String) 
        = new Person(firstName, lastName)

    def unapply(p: Person): (String,String) 
        = (p.firstName, p.lastName)
}

18. How does it work under-the-hood, when we create an instance of a Class without using ‘new’ keyword in Scala? When do we go for this approach? How to declare private constructors in Scala?

In Scala, when we create an instance of a Class without using ‘new’ keyword, internally it make a call to appropriate apply method available in Companion object. Here appropriate apply method means that matched with parameters.

When do we choose this option: When we need to provide private constructor and we need to avoid using ‘new’ keyword, we can implement only apply method with same set of parameters and allow our class users to create it without new keyword.

19. How do we declare a private Primary Constructor in Scala? How do we make a call to a private Primary Constructor in Scala?

In Scala, we can declare a private Primary Constructor very easily. Just define a Primary Constructor as it is and add ‘private’ just after class name and before parameter list as shown below:

class Person private (name: String)
object Person{
 def apply(name: String) = new Person(name)
}

As it’s a private constructor, we cannot call it from outside. We should provide a factory method (that is apply method) as shown above and use that constructor indirectly.

20. Does a Companion object access private members of it’s Companion class in Scala?

Generally, private members means accessible only within that class. However Scala’s Companion class and Companion Object has provided another feature.

In Scala, a Companion object can access private members of it’s Companion class and Companion class can access it’s Companion object’s private members.

21. What is the main design decision about two separate keywords: class and object in Scala? How do we define Instance members and Static members in Scala?

In Scala, we use class keyword to define instance members and object keyword to define static members. Scala does not have static keyword, but still we can define them by using object keyword.

The main design decision about this is that the clear separation between instance and static members. Loosely coupling between them. And other major reason is to avoid static keyword so that Scala will become a Pure-OOP Language.

22. What is object in Scala? Is it a singleton object or instance of a class?

Unlike Java, Scala has two meanings about ‘object’. Don’t get confuse about this, I will explain it clearly. In Java, we have only one meaning for object that is “An instance of a class”.

  • Like Java, the first meaning of object is “An instance of a class”.
val p1 = new Person("Scala","Java")
or 
val p1 = Person("Scala","Java")
  • Second meaning is that object is a keyword in Scala. It is used to define Scala Executable programs, Companion Objects, Singleton Objects etc.

23. What is a Companion Object in Scala? What is a Companion Class in Scala? What is the use of Companion Object in Scala?

In simple words, if a Scala class and object shares the same name and defined in the same source file, then that class is known as “Companion Class” and that object is known as “Companion Object”.

When we create a Class by using Scala “class” keyword and Object by using Scala “object” keyword with same name and within the same source file, then that class is known as “Companion Class” and that object is known as “Companion Object”.

Example:-
Employee.scala

class Employee{ }
object Employee{ }

In Scala, The main purpose of Companion Object is to define apply methods and avoid using new keyword in creating an instance of that Companion class object.

24. How to implement interfaces in Scala?

There is no interface concept in Scala. Even, Scala doesn’t have interface keyword. Scala has a more powerful and flexible concept i.e. trait for this purpose

25. What is Range in Scala? How to create a Range in Scala?

Range is a Lazy Collection in Scala. Range is a class available in ‘scala’ package like ‘scala.Range’. It is used to represent a sequence of integer values. It is an ordered sequence of integers.

Example:-

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

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

26. How many values of type Nothing have in Scala?

  • In Scala, Nothing type have no values that is zero.
  • It does not have any values.
  • It is a subtype of all Value classes and Reference classes.
  • There are no instances of Nothing.
  • Nil is defined using Nothing (See below for example).
  • None is defined using Nothing.
object None extends Option[Nothing]

object Nil extends List[Nothing]

27. How many values of type Unit have in Scala?

In Scala, Unit is something similar to Java’s void keyword. It is used to represent “No value exists”. It has one and only one value that is ().

28. What is a pure function? What is impure function?

A pure function is a function without any observable side-effects. That means it returns always same results irrespective how many times we call it with same inputs.

A pure function always gives same output for the same inputs.

For Example:-

scala> 10 + 20
res0: Int = 30

scala> 10 + 20
res0: Int = 30

Here “+” a pure function available in Int class. It gives same result 30 for same inputs 10 and 20, irrespective how many times we call it.

A more accurate way of saying this is:

  1. Output depends only on input
  2. No side effects

You can represent that as an image like this:

or more simply, like this:

Examples of pure functions

Mathematical functions are great examples of pure functions because it’s pretty obvious that “output depends only on input.” Methods like these in scala.math._ are all pure functions:

  • abs
  • ceil
  • max
  • min

Because a Scala String is immutable, every method available to a String is a pure function, including:

  • charAt
  • isEmpty
  • length
  • substring

Many methods that are available on Scala’s collections’ classes fit the definition of a pure function, including the common ones:

  • drop
  • filter
  • map
  • reduce

Examples of impure functions

Conversely, the following functions are impure.

The foreach method is impure. foreach is used only for its side effects, which you can tell by looking at its signature on the Seq class:

def foreach(f: (A) => Unit): Unit 

Date and time related methods like getDayOfWeekgetHour, and getMinute are all impure because their output depends on something other than their inputs. Their results rely on some form of hidden I/O.

Methods on the scala.util.Random class like nextInt are also impure because their output depends on something other than their inputs.

In general, impure functions do one or more of these things:

  • Read hidden inputs (variables not explicitly passed in as function input parameters)
  • Write hidden outputs
  • Mutate the parameters they are given
  • Perform some sort of I/O with the outside world

By looking at function signatures only, there are two ways you can identify many impure functions:

  • They don’t have any input parameters
  • They don’t return anything (or they return Unit in Scala, which is the same thing)

For example, here’s the signature for the println method of the Scala Predefobject:

def println(x: Any): Unit

Because println is such a commonly-used method you already know that it writes information to the outside world.

Similarly when you look at the “read*” methods that were formerly in Predef (and are now in scala.io.StdIn), you’ll see that a method like readLinetakes no input parameters, which is also a giveaway that it is impure:

def readLine(): String

Because it takes no input parameters, the mantra, “Output depends only on input” clearly can’t apply to it.

Simply stated:

  • If a function has no input parameters, how can its output depend on its input?
  • If a function has no result, it must have side effects: mutating variables, or performing some sort of I/O.

While this is an easy way to spot many impure functions, other impure methods can have both (a) input parameters and (b) a non-Unit return type, but still be impure because they read variables outside of their scope, mutate variables outside of their scope, or perform I/O.

29. In FP, What is the difference between a function and a procedure?

Both are used to perform computation, however they have one major difference in Functional Programming world.

A function is a computation unit without side-effect where as a Procedure is also a computation unit with side-effects. Also, function which do not return anything can be called as procedures.

30. What is the use of ‘yield’ keyword in Scala’s for-comprehension construct?

We can use ‘yield’ keyword in Scala’s for-comprehension construct. ‘for/yield’ is used to iterate a collection of elements and generates new collection of same type. It does not change the original collection. It generates new collection of same type as original collection type.

For example, if we use ‘for/yield’ construct to iterate a List then it generates a new List only.

scala> val list = List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> for(l <- list) yield l*2
res0: List[Int] = List(2, 4, 6, 8, 10)

31. What is guard in Scala’s for-comprehension construct?

In Scala, for-comprehension construct has an if clause which is used to write a condition to filter some elements and generate new collection. This if clause is also known as “Guard”.

If that guard is true, then add that element to new collection. Otherwise, it does not add that element to original collection.

Example:- For-comprehension Guard to generate only Even numbers into new collection.

scala> val list = List(1,2,3,4,5,6,7,8,9,10)
list: List[Int] = List(1, 2, 3, 4, 5 , 6 , 7 , 8 , 9 , 10)

scala> for(l <- list if l % 2 =0 ) yield l
res0: List[Int] = List(2, 4, 6, 8, 10)

//Note: Above requirement of generating only Even number can be done using filter method also.
scala> list.filter(x => x%2==0)
res13: List[Int] = List(2, 4, 6, 8, 10)

32. What is Option in Scala? What are Some and None? What is Option/Some/None Design Pattern in Scala?

In Scala, Option is used to represent optional values that is either exist or not exist.
Option is an abstract class. Option has two subclasses: Some and None. All three (Option, Some and None) are defined in “scala” package like “scala.Option”.

Option contains either zero or one element. If Option contains zero elements that is None. If Option contains one element, that is Some.

Some is used to represent existing value. None is used to represent non-existent value.
Example:-

def get(val index: Int): Option[String]

Let us assume that this method is from List. This method has a return type of Option[String]. If List contains elements, this get method returns “Some[String]” element available in that index position. Otherwise, it returns “None” (that is no elements).

Example:- Some class has a get method, which is used to get the exact value.

val l = ListBuffer(1,2,3)
println(l.lastOption);   // ==> Some(3)
println(l.lastOption.get)  // ==> 3

Some is a case class and None is an Object. As both are case class/object, we can use them in Pattern Matching very well.

A simple Scala Option example:

def toInt(in: String): Option[Int] = {
    try {
        Some(Integer.parseInt(in.trim))
    } catch {
        case e: NumberFormatException => None
    }
}

Here’s how this toInt function works:

  • It takes a String as a parameter.
  • If it can convert the String to an Int, it does so, returning it as Some(Int).
  • If the String can’t be converted to an Int, it returns None.

If you’re a consumer of this toInt function, your code will look something like this:

toInt(someString) match {
    case Some(i) => println(i)
    case None => println("That didn't work.")
}
object ScalaPractiseObject {
  def toInt(in: String): Option[Int] = {
    try {
      Some(Integer.parseInt(in.trim))
    } catch {
      case e: NumberFormatException => None
    }
  }
  def display(in:String) {
    toInt(in) match {
      case Some(i) => println(i)
      case None => println("That didn't work.")
    }
  }
  def main(args: Array[String]): Unit = {
    display("123")
    display("abc")
  }
}

Let’s assume you want to get the sum of a List that contains a bunch of String values, and some of those strings can be converted to Int values, and some can’t:

val bag = List("1", "2", "foo", "3", "bar")

Seems like the code should look really ugly, right? Wrong. 

In Scala we can write a “sum” expression in just one line of easy to read code:

val sum = bag.flatMap(toInt).sum

Because (a) we’ve written toInt to return either a Some[Int] or None value, and (b) flatMap knows how to handle those values, writing this line of code is a piece of cake, and again, it’s easy to read and understand.

Now that shows how the Option/Some/None pattern really shines!

Option are best to use when function can return null value.

Simply stated, instead of returning one object when a function succeeds and null when it fails, your function should instead return an instance of an Option, where the instance is either:

  1. An instance of the Scala Some class
  2. An instance of the Scala None class

Because Some and None are both children of Option, your function signature just declares that you’re returning an Option.

While using Option is generally a much better approach, one weakness of this approach is that the Option/Some/None approach doesn’t tell you why something failed, that is, why you got a None instead of a Some.

33. What is Either in Scala? What are Left and Right in Scala? Explain Either/Left/Right Design Pattern in Scala?

  • Either works just like Option, with a difference being that with Either you can return a String that describes the problem that occurred.
  • In Scala, Either is an abstract class. It is used to represent one value of two possible types. It takes two type parameters: Either[A,B].
  • Instances of Either are either an instance of Left or Right.
  • It exactly have two subtypes: Left and Right. If Either[A,B] represents an instance A that means it is Left. If it represents an instance B that means it is Right.

Here’s a quick comparison of the Option and Either approaches:

  • Either is just like Option
  • Right is just like Some
  • Left is just like None, except you can include content with it to describe the problem

Here’s a look at how Either works in a simple example:

object EitherLeftRightExample {

  def divideXByY(x: Int, y: Int): Either[String, Int] = {
    if (y == 0) Left("Dude, can't divide by 0")
    else Right(x / y)
  }

  def display(left: Int, right: Int) {
    divideXByY(left, right) match {
      case Left(s) => println("Answer: " + s)
      case Right(i) => println("Answer: " + i)
    }
  }

  def main(args: Array[String]): Unit = {
    println(divideXByY(1, 0)) // => Left(Dude, can't divide by 0)
    println(divideXByY(1, 1)) // => Right(1)
    display(1, 0) // => Answer: Dude, can't divide by 0
    display(1, 1) // => Answer: 1
  }
}

In that example, the method divideXByY returns an Either, specifically this Either:

Either[String, Int]

In this example, the thing on the left is a String, and the thing on the right is an Int. Inside the function, the thing on the left is represented by Left, and the thing on the right is represented by Right.

If you’re familiar with the Option/Some/None pattern, you can see that using Either is only a slight difference from using that pattern. Again, the intent of using Either is to pass a message back about what went wrong, so you can return the error message from an exception, or anything else you want to return with the Left instance.

A common use of Either is as an alternative to Optionfor dealing with possible missing values. In this usage, scala.None is replaced with a Left which can contain useful information. Right takes the place of Some. Convention dictates that Left is used for failure and Right is used for success.

34. What is the equivalent construct of Scala’s Option in Java SE 8? What is the use of Option in Scala?

Scala’s Option is similar to Java SE 8’s Optional. Java SE 8 has introduced a new utility class Optional to represent existing or non-existing of some value. Optional is available in java.util package.

Both Scala’s Option and Java SE 8’s Optional are used to represent optional values. Both are used to avoid unwanted null checks and NullPointerException.

35. Like Hibernate for Java-based applications, What are the Popular ORM Frameworks available to use in Play/Scala based applications?

Like JPA, Hibernate and Toplink etc ORM Frameworks for Java-based applications, There are many ORM frameworks to use in Play/Scala based applications.
Popular ORM frameworks for Play/Scala based applications:

  • Slick
  • Anorm
  • SORM(Scala ORM)
  • Squeryl

36. How Scala supports both Highly Scalable and Highly Performance applications?

As Scala supports Multi-Paradigm Programming(Both OOP and FP) and uses Actor Concurrency Model, we can develop very highly Scalable and high-performance applications very easily.

37. Why Scala is better than Java? What are the advantages of Scala over Java (Java 8)? Compare to Java What are the major advantages or benefits of Scala?

Because Scala supports the following extra features, it is better than Java 8:

  • Full FP Features
  • More Expression Language
  • Pattern Matching
  • Better support for Akka Actor Model
  • Automatic resolution for Inheritance Diamond Problem with Traits
  • Asynchronous and Non-blocking IO programming using Akka Framework
  • Fully Reactive Streaming API

38. What is an Anonymous Function In Scala? What is a Function Literal in Scala? What are the advantages of a Anonymous Function/Function Literal in Scala?

Anonymous Function is also a Function but it does not have any function name. It is also known as a Function Literal.
The advantages of a Anonymous Function/Function Literal in Scala:

  • We can assign a Function Literal to variable.
var myfc1 = (str1:String, str2:String) => str1 + str2
val mul = (a:Int) => a*3
  • We can pass a Function Literal to another function/method.
// A function which contain anonymous 
// function as a parameter 

val list = List(1,2,3)
list.map(x=> mul(x)) // => List(3,6,9)

OR

def myfunction(fun:(String, String)=> String) =
{ 
     fun("Dog", "Cat") 
} 
  • We can return a Function Literal as another function/method result/return value. The following code declares an anonymous function that takes a Stringargument and returns a String:
(s: String) => { prefix + " " + s }
// Example1: Scala program to illustrate the anonymous method 
object AnonyMousExample
{ 
	def main(args: Array[String]) 
	{ 
		val list = List(5, 10, 15) 
		val mul = (i:Int) => i*3 
		val result = list.map(y => mul(y)) 
		println("Multiplied List is: " + result) 
	} 
} 

Output: Multiplied List is: List(15, 30, 45)
// Example2: Scala program to illustrate the anonymous method 
object Main 
{ 
	def main(args: Array[String]) 
	{ 
		// Creating anonymous functions 
		// with multiple parameters Assign 
		// anonymous functions to variables 
		var myfc1 = (str1:String, str2:String) => str1 + str2
		
		// An anonymous function is created 
		// using _ wildcard instead of 
		// variable name because str1 and 
		// str2 variable appear only once 
		var myfc2 = (_:String) + (_:String) 
		var myfc3 = (_:Int) + (_:Int) 		
              
		// Here, the variable invoke like a function call 
		println(myfc1("Scala", "Java")) // => ScalaJava
		println(myfc2("Scala", "Java")) // => ScalaJava 
		println(myfc3(1,2)) // => 3
	} 
} 
// Example3: Scala program to illustrate anonymous method 
object Main 
{ 
	def main(args: Array[String]) 
	{ 
		// Creating anonymous functions 
		// without parameter 
		var myfun1 = () => {"Harshit"} 
		println(myfun1) // => Harshit
		
		// A function which contain anonymous 
		// function as a parameter 
		def myfunction(fun:(String, String)=> String) =
		{ 
			fun("Dog", "Cat") 
		} 
		
		// Explicit type declaration of anonymous 
		// function in another function 
		val f1 = myfunction((str1: String, 
					str2: String) => str1 + str2) 
		
		// Shorthand declaration using wildcard 
		val f2 = myfunction(_ + _) 
		println(f1) 
		println(f2) 
	} 
}

39. How to create a method that returns a function in Scala?

Problem

You want to return a function (algorithm) from another Scala function or method.

Solution

Define a function that returns an algorithm (an anonymous function), assign that to a new function, and then call that new function.

The following code declares an anonymous function that takes a Stringargument and returns a String:

(s: String) => { prefix + " " + s }

You can return that anonymous function from the body of another function as follows:

def saySomething(prefix: String) = (s: String) => {
    prefix + " " + s
}

Because saySomething returns a function, you can assign that resulting function to a variable. The saySomething function requires a Stringargument, so give it one as you create the resulting function sayHello:

val sayHello = saySomething("Hello")

The sayHello function is now equivalent to your anonymous function, with the prefix set to hello. Looking back at the anonymous function, you see that it takes a String parameter and returns a String, so you pass it a String:

sayHello("Al")

Here’s what these steps look like in the REPL:

scala> def saySomething(prefix: String) = (s: String) => {
     |   prefix + " " + s
     | }
saySomething: (prefix: String)String => java.lang.String

scala> val sayHello = saySomething("Hello")
sayHello: String => java.lang.String = <function1>

scala> sayHello("Al")
res0: java.lang.String = Hello Al

Discussion

If you’re new to functional programming, it can help to break this down a little. You can break the expression down into its two components. On the left side of the = symbol you have a normal method declaration:

def saySomething(prefix: String)

On the right side of the = is a function literal (also known as an anonymous function):

(s: String) => { prefix + " " + s }

Another example

As you can imagine, you can use this approach any time you want to encapsulate an anonymous function inside a function. A bit like a Factory or Strategy pattern, the function your method returns can be based on the input parameter it receives. For example, create a greeting method that returns an appropriate greeting based on the language specified:

def greeting(language: String) = (name: String) => {
    language match {
        case "english" => "Hello, " + name
        case "spanish" => "Buenos dias, " + name
    }
}

If it’s not clear that greeting is returning a function, you can make the code a little more explicit:

def greeting(language: String) = (name: String) => {
    val english = () => "Hello, " + name
    val spanish = () => "Buenos dias, " + name
    language match {
        case "english" => println("returning 'english' function")
                          english()
        case "spanish" => println("returning 'spanish' function")
                          spanish()
    }
}

Here’s what this second method looks like when it’s invoked in the REPL:

scala> val hello = greeting("english")
hello: String => java.lang.String = <function1>

scala> val buenosDias = greeting("spanish")
buenosDias: String => java.lang.String = <function1>

scala> hello("Al")
returning 'english' function
res0: java.lang.String = Hello, Al

scala> buenosDias("Lorenzo")
returning 'spanish' function
res1: java.lang.String = Buenos dias, Lorenzo

40. What is an Higher-Order Function (HOF)?

Higher Order Function (HOF) is also a function but which performs one, two or both of the following things:

  • Take other functions as arguments
  • Return functions as their results
// Scala program of higher order function 
object HOF
{ 
	// Main method 
	def main(args: Array[String]) 
	{ 
	
		// Creating a list of numbers 
		val num = List(5, 10, 15) 
	
		// Defining a method 
		def multiplyValue(y:Int) = y * 3
	
		// Creating a higher order function 
		// that is assigned to the variable 
		val result = num.map(y => multiplyValue(y)) 
	
		// Displays output 
		println("Multiplied List is: " + result) 
	} 
} 

Output: Multiplied List is: List(15, 30, 45)

41. What are the Java’s OOP constructs not supported by Scala? What are the Scala’s OOP constructs not supported by Java? What are the new OOPs constructs introduced by Scala, but not supported by Java?

Java’s OOP constructs, which are not supported by Scala:

  • There is no interface concept in Scala
  • There is no Enum concept in Scala

Scala’s OOP constructs, which are not supported by Java:
OR
The new OOPs constructs introduced by Scala, but not supported by Java:

  • Scala Traits
  • Solving Inheritance Diamond Problem automatically.

42. What is Extractor in Scala? What is the difference between Constructor and Extractor in Scala? What is the use of Extractor in Scala?

Not only in Java and Scala, in almost all OOP languages Constructor is used to create (or assemble) an object or an instance of a Class using it’s parameters (or components). Extractor is quite opposite to Constructor.

In Scala, Extractor is used to decompose or disassemble an object into it’s parameters (or components).

In Scala, apply method is a Constructor. Internally, Extractor uses unapply method to decompose an objects into it’s parts (or parameters). In Scala, Extractor is mainly used in Pattern Matching concept. 

43. What is the use of ‘???’ in Scala-based Applications?

This ‘???’ three question marks is not an operator, a method in Scala. It is used to mark a method which is ‘In Progress’ that means Developer should provide implementation for that one.

This method is define in scala.PreDef class as shown below:

def ??? : Nothing = throw new NotImplementedError

If we run that method without providing implementation, then it throws ‘NotImplementedError’ error as shown below:

scala> val a = ???
scala.NotImplementedError: an implementation is missing
....

44. Explain the main difference between List and Stream in Scala Collection API? How do we prove that difference? When do we choose Stream?

In Scala, both List and Stream are from Collection API and works almost similar. Both are Immutable collections.

However, there is one main difference between List and Stream in Scala Collection API: That is List elements are evaluated Eagerly and Stream elements are evaluated Lazily that means when we access them.

scala> var list1 = List(1,2,3,4)
list1: List[Int] = List(1, 2, 3, 4)

Here we can observe that all List elements evaluated at the time of creating List object. However, if we do same thing on Stream, we cannot see all elements. We can see only first evaluated element and remaining elements are evaluated lazily as shown below:

scala> var s1 = Stream(1,2,3,4)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

When we want Lazy collection to evaluate elements only when we access them then it’s better to use Stream.

45. What is the difference between :: and #:: in Scala? What is the difference between ::: and #::: in Scala?

In Scala Collection API,

  • :: and ::: are methods available in List class.
  • #:: and #::: are methods available in Stream class
  • In List class, :: method is used to append an element to the beginning of the list.
scala> var list1 = List(1,2,3,4)
list1: List[Int] = List(1, 2, 3, 4)

scala> list1 = 0 :: list1
list1: List[Int] = List(0, 1, 2, 3, 4)
  • In List class, ::: method is used to concatenate the elements of a given list in front of this list.
scala> var list1 = List(3,4,5)
list1: List[Int] = List(3, 4, 5)

scala> val list2 = List(1,2) ::: list1
list2: List[Int] = List(1, 2, 0, 1, 2, 3, 4)
  • In Stream class, #:: method is used to append a given element at beginning of the stream. Only this newly added element is evaluated and followed by lazily evaluated stream elements.
scala> var s1 = Stream(1,2,3,4)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> s1 = 0 #:: s1
s1: scala.collection.immutable.Stream[Int] = Stream(0, ?)
  • In Stream class, #::: method is used to concatenate a given stream at beginning of the stream. Only this newly added element is evaluated and followed by lazily evaluated stream elements.
scala> var s1 = Stream(1,2,3,4)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> val s2 = Stream(-1,0) #::: s1
s2: scala.collection.immutable.Stream[Int] = Stream(-1, ?)
  • :: method works as a cons operator for List class and #:: method words as a cons operator for Stream class. Here ‘cons’ stands for construct.
  • ::: method works as a concatenation operator for List class and #::: method words as a concatenation operator for Stream class.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.