300+ TOP SCALA Interview Questions and Answers

SCALA Interview Questions for freshers experienced :-

1. What is Scala?

Scala is a Java-based Hybrid programming language which is the fusion of both Functional and Object-Oriented Programming Language features. It can integrate itself with Java Virtual Machine and compile the code written.

2. How Scala is both Functional and Object-oriented Programming Language?

Scala treats every single value as an Object which even includes Functions. Hence, Scala is the fusion of both Object-oriented and Functional programming features.

3.Write a few Frameworks of Scala

Some of the Frameworks supported by Scala are as follows:

  • Akka Framework
  • Spark Framework
  • Play Framework
  • Scalding Framework
  • Neo4j Framework
  • Lift Framework
  • Bowler Framework

4. Explain the types of Variables in Scala? And What is the difference between them?

The Variables in Scala are mainly of two types:

Mutable Variables

  1. We Declare Mutable Variables by using the var keyword.
  2. The values in the Mutable Variables support Changes

Immutable Variables

  1. We declare Immutable Variables using the val keyword.
  2. The values in Immutable Variables do not support changes.

5. Explain Streams in Scala.

In simple words, we define Stream as a Lazy list which evaluates the elements only when it needs to. This sort of lazy computation enhances the Performance of the program.

6. Mention the Advantages of Scala

Some of the major Advantages of Scala are as follows:

  • It is highly Scalable
  • It is highly Testable
  • It is highly Maintainable and Productive
  • It facilitates Concurrent programming
  • It is both Object-Oriented and Functional
  • It has no Boilerplate code
  • Singleton objects are a cleaner solution than Static
  • Scala Arrays use regular Generics
  • Scala has Native Tuples and Concise code

7. Explain the Operators in Scala

The following are the Operators in Scala:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators

8. What is Recursion tail in Scala?

‘Recursion’ is a function that calls itself. For example, a function ‘A’ calls function ‘B’, which calls the function ‘C’. It is a technique used frequently in Functional programming. In order for a Tail recursive, the call back to the function must be the last function to be performed.

9. Explain the use of Tuples in Scala?

Scala tuples combine a Finite number of items together so that the programmer can Pass a tuple around as a Whole. Unlike an Array or List, a tuple is Immutable and can hold objects with different Datatypes.

10. How is a Class different from an Object?

Class combines the data and its methods whereas an Object is one particular Instance in a class.

SCALA Interview Questions
SCALA Interview Questions

11. Why do we need App in Scala?

App is a helper class that holds the main method and its Members together. The App trait can be used to quickly turn Objects into Executable programs. We can have our classes extend App to render the executable code.

object Edureka extends App{
println(“Hello World”)
}

12. What are Higher-order functions?

A Higher-order function is a function that does at least one of the following: takes one or more Functions as Arguments, returns a Function as its result.

13. Explain the scope provided for variables in Scala.

There are three different scopes depending upon their use. Namely:

Fields:

Fields are variables declared inside an object and they can be accessed anywhere inside the program depending upon the access modifiers. Fields can be declared using var as well as val.

Method Parameters:

Method parameters are strictly Immutable. Method parameters are mainly used to Pass values to the methods. These are accessed inside a method, but it is possible to access them from outside the method provided by a Reference.

Local Variables:

Local variables are declared inside a method and they are accessible only inside the method. They can be accessed if you return them from the method.

14. What is a Closure?

Closure is considered as a Function whose return value is Dependent upon the value of one or more variables declared outside the closure function.

Course Curriculum
Apache Spark and Scala Certification Training
Instructor-led SessionsReal-life Case StudiesAssessmentsLifetime Access
Example:

val multiplier = (i:Int) => i * 10
Here the only variable used in the function body, i * 10 , is i, which is defined as a parameter to the function

15. Explain Traits in Scala.

A Trait can be defined as a unit which Encapsulates the method and its variables or fields. The following example will help us understand in a better way.

trait Printable{
def print()
}
class A4 extends Printable{
def print(){
println(“Hello”)
}
}
object MainObject{
def main(args:Array[String]){
var a = new A4()
a.print()
}
}

16. Mention how Scala is different from Java

A few scenarios where Scala differs from Java are as follows:

  • All values are treated as Objects.
  • Scala supports Closures
  • Scala Supports Concurrency.
  • It has Type-Inference.
  • Scala can support Nested functions.
  • It has DSL support [Domain Specific Language]
  • Traits

17. Explain extend Keyword

You can extend a base Scala class and you can design an Inherited class in the same way you do it in Java by using extends keyword, but there are two restrictions: method Overriding requires the override keyword, and only the Primary constructor can pass parameters to the base Constructor. Let us understand by the following example

println(“How to extend abstract class Parent and define a sub-class of Parent called Child”)
class Child=(name:String)extends Parent(name){
override def printName:Unit= println(name)
}
object Child {
def apply(name:String):Parent={
new Child(name)
}
}

18. Explain implicit classes with syntax
Implicit classes allow Implicit conversations with the class’s Primary constructor when the class is in scope. Implicit class is a class marked with the “implicit” keyword. This feature was introduced in with Scala 2.10 version.

//Syntax:
object {
implicit class Data type) {
def Unit = xyz
}
}

19. Explain the access Modifiers available in Scala

There are mainly three access Modifiers available in Scala. Namely,

Private:

The Accessibility of a private member is restricted to the Class or the Object in which it declared.
The following program will explain this in detail.

class Outer {
class Inner {
private def f() { println(“f”) }
class InnerMost {
f() // OK
}
}
(new Inner).f() // Error: f is not accessible
}

Protected:

A protected member is only Accessible from Subclasses of the class in which the member is defined.
The following program will explain this in detail.

package p
class Super {
protected def f() { println(“f”) }
}
class Sub extends Super {
f()
}
class Other {
(new Super).f() // Error: f is not accessible
}
}

Public:

Unlike Private and Protected members, it is not required to specify Public keyword for Public members. There is no explicit modifier for public members. Such members can be accessed from Anywhere.
Following is the example code snippet to explain Public member

class Outer {
class Inner {
def f() { println(“f”) }
class InnerMost {
f() // OK
}
}
(new Inner).f() // OK because now f() is public
}

20. What is a Monad in Scala?

A Monad is an object that wraps another object. You pass the Monad mini-programs, i.e functions, to perform the data manipulation of the underlying object, instead of manipulating the object directly. Monad chooses how to apply the program to the underlying object.

21. Explain the Scala Anonymous Function.

In the Source code, Anonymous functions are called ‘Function literals’ and at run time, function literals are instantiated into objects called Function values. Scala provides a relatively easy Syntax for defining Anonymous functions.

//Syntax
(z:Int, y:Int)=> z*y
Or
(_:Int)*(_Int)

22. How do I Append data in a list?

In Scala to Append into a List, We have the following methods:

use “:+” single value
var myList = List.empty[String]
myList :+= “a”

23. Why Scala prefers Immutability?

Scala prefers Immutability in design and in many cases uses it as default. Immutability can help when dealing with Equality issues or Concurrent programs.

24. Give some examples of Packages in Scala

The three important and default Packages in Scala are as follows:

  • Java.lang._ : Java.lang._ package in Java. Provides classes that are fundamental to the design of the Java programming language.
  • Java.io._ : Java.io._ Package used to import every class in Scala for input-output resources.
  • PreDef: Predef provides type aliases for types which are commonly used, such as the immutable collection types Map, Set, and the List constructors

25. Why is an Option used in Scala?

Option in Scala is used to Wrap the Missing value.

26. Mention the Identifiers in Scala.

There are four types of Scala Identifiers:

  • Alphanumeric identifiers
  • Operator identifiers
  • Mixed identifiers
  • Literal identifiers

//Scala program to demonstrate Identifiers in Scala.
object Main
{
//Main method
def main(args: Array[String])
{
//Valid Identifiers
var ‘name = “Hari”‘
var age = 20;
var Branch = “Computer Science”
println()
println()
println()
}
}

27. How do you define a function in Scala?

def keyword is used to define the Function in Scala.

object add {
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}

28. How is the Scala code compiled?

Code is written in Scala IDE or a Scala REPL, Later, the code is converted into a Byte code and transferred to the JVM or Java Virtual Machine for compilation.

Big Data Training

29. Explain the functionality of Yield.

Yield is used with a loop, Yield produces a value for each iteration. Another way to do is to use map/flatMap and filter with nomads.

for (i <- 1 to 5) yield i

30. Differentiate between Null, Nil, None and Nothing

They appear similar but different in their behaviour:

  1. Null Nil None Nothing
  2. Null represents the absence of a value. Nil denotes the end a List None is the value of an Option with no value. Nothing is lowest type in type System.

31. Explain If-Else-If terminology

If-Else-If statement executes one of the three statements.

Example:

object Demo {
def main(args: Array[String]) {
var x = 30;
if( x == 10 ){
println(“Value of X is 10”)
} else if( x == 20 ){
println(“Value of X is 20”);
} else if( x == 30 ){
println(“Value of X is 30”);
} else{
println(“This is else statement”);
}
}
}

32. Describe Loops in Scala.

There are mainly three types of loops in Scala.

  • While Loop: Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
  • Do-While: Like a while statement, except that it tests the condition at the end of the loop body.
  • For: Executes a sequence of statements multiple times and abbreviated the code that manages the loop variable.
  • Break: Break is a loop control statement which Terminates the loop statement and transfers execution to the statement immediately following the loop.

33. Generate an Infinite loop

A loop becomes an Infinite loop if a condition never becomes false. If you are using Scala, the while loop is the best way to implement an infinite loop.

The following program implements an infinite loop.

object Demo {
def main(args: Array[String]) {
var a = 10;
//An infinite loop.
while( true ){
println( “Value of a: ” + a );
}
}
}

34. What is the Syntax for function declaration in Scala?

The Syntax for function declaration is as follows:

def functionName ([list of parameters]) : [return type] = {
function body
return [expression]
}
Here, the return type is any valid Scala data type and we separate the list of parameters by comma and list of parameters and return type are optional. Very similar to Java, we use a return statement along with an expression in case function returns a value.

35. How do I Concatenate two Strings?

There are three methods to perform string concatenation in Scala

string1.concat(string2);
“My name is “.concat(“Zara”);
“Hello,” + ” world” + “!”

36. Explain any five string methods.

Following are few String Methods in Scala.

String trim(): Returns a copy of the string, with leading and trailing whitespace omitted.
String toUpperCase: Converts all of the characters in this String to upper case using the rules of the given Locale.
Char[] to CharArray(): Converts this string to a new character array.
String[] split(String regex): Splits this string around matches of the given regular expression.
Int length(): returns the length of this string.

37. Explain how to create Arrays

We use the following methods to create arrays in Scala:

We use ofDim to declare multidimensional arrays.

var myMatrix = ofDim[Int](3,3)
We use Range() method to generate an array containing a sequence of increasing integers in a given range.
def range( start: Int, end: Int, step: Int ): Array[Int]

range (10, 20, 2)

38. What is Map in Scala?

Map is a collection of key/value pairs. Scala retrieves a Value based on its Key.

val colors = Map(“red” -> “#FF0000”, “azure” -> “#F0FFFF”)

39. Explain Exception Handling in Scala

Throw Exception: Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword as follows.

  • Throw new IllegalArgumentException
  • Catching an Exception:
  • Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks. Try the following example program to handle the exception.

Example:

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Demo {
def main(args: Array[String]) {
try {
val f = new FileReader(“input.txt”)
} catch {
case ex: FileNotFoundException ={
println(“Missing file exception”)
}
case ex: IOException = {
println(“IO Exception”)
}
}
}
}
So, with this, we finished some questions on the Intermediate Level.
Now, Let us move to the next level of interview questions which happen to be the Advanced Level Interview Questions.

40. Explain Pattern Matching in Scala through an example

A Pattern match includes a sequence of alternatives, each starting with the Keyword case. Each alternative includes a Pattern and one or more Expressions, Scala evaluates whenever a pattern matches. An arrow symbol => separates the pattern from the expressions.

Try the following example program, which shows how to match against an integer value.

object Demo {
def main(args: Array[String]) {
println(matchTest(3))
}
def matchTest(x: Int): String = x match {
case 1 = “one”
case 2 = “two”
case _ = “other”
}
}

41. Explain Extractors in Scala

  • Course Curriculum
  • Apache Spark and Scala Certification Training
  • Weekday / Weekend Batches
  • An Extractor in Scala is an object that has a method called unapply as one of its members. The purpose of that unapply method is to match the value and take it apart.

42. What is the result of x+y*z and why?

Similar to any other programming language, Scala also follows Presidency and Priority tables. According to the tables, Scala Performs the operations as follows.

Scala evaluates y*z first.
Then adds (y*z) with x

43. What is an Auxiliary constructor

We use Auxiliary constructor in Scala for Constructor Overloading. The Auxiliary Constructor must call either previously defined auxiliary constructors or primary constructor in the first line of its body.

44. Explain recursion through a program

def factorial_loop(i: BigInt): BigInt = {
var result = BigInt(1)
for (j- 2 to i.intValue)
result *= j
result
}
for (i – 1 to 10)
format(“%s: %sn”, i, factorial_loop(i))

45. Explain Que with example

Queue is a Data Structure similar to Stack except, it follows First In First Out procedure for data processing. In Scala, to work with Queues, you need to import a library called,

import scala.collection.mutable.Queue

val empty = new Queue[Int]

SCALA Questions and Answers Pdf Download

300+ TOP Scala Interview Questions and Answers

Q1. 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)
}

Q2. 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 use 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.

NOTE:- If you want to learn about Scala’s Constructors, please refer my Scala posts at: Primary Constructor and Auxiliary Constructor.

Q3. How To Implement Interfaces In Scala?

As we know from Java background, we use interface to define contact.

However, 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.

Q4. What Is Call-by-name? Does Scala And Java Support Call-by-name? What Is The Difference Between Call-by-value And Call-by-name Function Parameters?

Call-by-name means evaluates method/function parameters only when we need them or we access them. If we don’t use them, then it does not evaluate them.

Scala supports both call-by-value and call-by-name function parameters. However, Java supports only call-by-value, but not call-by-name.

Difference between call-by-value and call-by-name:

The major difference between these two are described below:

  • In Call-by-name, the function parameters are evaluated only whenever they are needed but not when the function is called.
  • In Call-by-value, the function parameters are evaluated when the function is called.
  • In Call-by-value, the parameters are evaluated before executing function and they are evaluated only once irrespective of how many times we used them in that function.
  • In Call-by-name, the parameters are evaluated whenever we access them and they are evaluated each time we use them in that function.
  • Scala Syntax Differences

Call-by-value:

1 def myFunction(a: Int, b: Int) { }

Here both a and b are Call-by-value parameters to myFunction.

Call-by-name:

1 def myFunction(a: Int, b: => Int) { }

Here both a is a Call-by-value parameter and b is Call-by-name to myFunction.

Q5. What Are The Advantages Of Play/scala Stack To Develop Web Applications?

The following are the major advantages of Play/Scala stack to develop web applications:

  • Open Source: Play is an Open-source free-software framework to develop web applications.
  • Better Productivity: Play framework’s Auto-reload feature improves Developer Productivity. No need to build, deploy and test our changes. Just do our changes and refresh the page to see our changes.
  • Stateless and Easy to Develop REST API: Play is HTTP based stateless model to serve web requests so it is very easy to develop REST API or RESTful Web Services.
  • Better Error-Handling: If we develop our web application using Play framework,it informs all errors in the browser in very useful format. It shows error message, the file location, line number where error occurred, highlighting the code-snippet to understand the error very easily.
  • High Performance and Better Scalability With Reactive: Play framework is developed by following Reactive design patterns and it is built on top of Netty sever to utilize Non-blocking IO Feature. Because of this feature, we can develop very highly Scalable and performance applications very easily.
  • Easy to Extend: Play is very flexible framework and supports developing plug-ins very easy to extend it’s features and functionality.
  • Highly Concurrency and Better Parallelism: As both Scala and Play supports Functional Programming, it is very easy to develop Highly Concurrency and Better Parallelism applications very easily because FP supports Immutability, Pure Functions (Functions without side-effects), Pattern Matching, Actor Model etc.
  • Better Reusability, Easy to Test and More Modular: As both Scala and Play supports Functional Programming, we can develop more modular and reusable applications. It is also very easy to test more modular applications.

Q6. What Are The Four Types Of Scala Identifiers ?

The four types of identifiers are

  • Alpha numeric identifiers
  • Operator identifiers
  • Mixed identifiers
  • Literal identifiers

Q7. What Is The Current Latest Version Of Scala? What Is The Major Change Or Update In Scala 2.12?

Current Scala’s stable is 2.11.@It supports Java SE 7.

The major change or update in Scala 2.12 version is that it supports Java SE 8 or later versions only. Scala 2.12 is not a binary compatible with the 2.11.x series. It’s still in Mile Stone Builds only.

Q8. If I Want To Become A Fullstack Scala Developer, Which Technology Stack I Should Learn?

If you want to become a Fullstack Scala Developer, you should learn the following technology stack:

  • Scala 2.11.7
  • Play 2.4.6 Framework
  • Akka 2.3 Framework
  • One Build Tool: SBT/Maven
  • One JS Framework: CoffeeScript/JavaScript
  • One IDE: IntelliJ IDEA 15/ Eclipse IDE 4.x
  • One TDD & BDD Framework: ScalaTest,Spec2,ScalaCheck,Mockito
  • Micro Services with Play and Scala
  • SCoverage
  • Scalastyle
  • Functional Programming Design Patterns
  • Machine Learning with Scala

Q9. 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 is a bounded collection in Scala, which 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)

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.

The combination of all these three definitions is known as Option/Some/None Design Pattern in Scala.

Q10. What Is Scala Anonymous Function?

In a source code, anonymous functions are called ‘function literals’ and at run time, function literals are instantiated into objects called function values.  Scala provides a relatively easy syntax for defining anonymous functions.

Q11. How Do I Append To The List?

In scala to append into a list, use “:+” single value

       var myList = List.empty[String]
       myList :+= “a”
       myList :+= “b”
       myList :+= “c”
       use++ for appending a list
       var myList = List.empty[String]
       myList ++= List(“a”, “b”, “c”)

Q12. What Are The Available Build Tools To Develop Play And Scala Based Applications?

The following three are most popular available Build Tools to develop Play and Scala Applications:

  • SBT
  • Maven
  • Gradle

Q13. What Is Either In Scala? What Are Left And Right In Scala? Explain Either/left/right Design Pattern In Scala?

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].

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.

This is known as Either/Left/Right Design Pattern in Scala.

Q14. Explain What Is Scala?

Scala is an object functional programming and scripting language for general software applications designed to express solutions in a concise manner.

Q15. What Are The Advantages Of Functional Programming (fp) Or Advantages Of Pure Functions?

The following are the Advantages of Functional Programming (FP) or Advantages of Pure Functions:

  • More Modular
  • Easier to understand Or Easier reason about
  • Easier to test
  • Less prone to bugs
  • Easier to reuse
  • Easier to Parallelism and generalize

Q16. When Compare To Normal Class, What Are The Major Advantages Or Benefits Of A Case-class?

The following are the major advantages or benefits of a Case class over Normal Classes:

  • Avoids lots of boiler-plate code by adding some useful methods automatically.
  • By default, supports Immutability because it’s parameters are ‘val’
  • Easy to use in Pattern Matching.
  • No need to use ‘new’ keyword to create instance of Case Class.
  • By default, supports Serialization and Deserialization.

Q17. What Is Case Class? What Is Case Object? What Are The Advantages Of Case Class?

Case class is a class which is defined with “case class” keywords. Case object is an object which is defined with “case object” 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. By default, Scala compiler prefixes “val” for all constructor parameters. That’s why without using val or var, Case class’s constructor parameters will become class members, it is not possible for normal classes.

Advantages of case class:

  • By default, Scala Compiler adds toString, hashCode and equals methods. We can avoid writing this boilerplate code.
  • 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.
  • We can use case classes in Pattern Matching.
  • By default, Case class and Case Objects are Serializable.

Q18. What Is Monad In Scala?

A monad is an object that wraps another object. You pass the Monad mini-programs, i.e functions, to perform the data manipulation of the underlying object, instead of manipulating the object directly.  Monad chooses how to apply the program to the underlying object.

Q19. What Are The Popular Scala-based Frameworks To Develop Restful Web Services Or Rest Api?

There are many Scala-Based Framework to develop RESTful Web Services. Most popular frameworks are:

  • Play Framework: n Play, we call REST API URLs as routes. We place all routes at once place in Play framework. It is a stateless web framework to develop REST API easily.
  • Scalatra Framework: It is very simple and easy Scala-based web framework to develop REST API
  • Spray Framework: It is very concise and built on top of Akka framework so it’s better to develop REST API using Actor Model.
  • Lift Framework: It allows routing using Pattern Matching concept.

Q20. What Is The Difference Between Var And Value?

In scala, you can define a variable using either a, val or var keywords.  The difference between val and var is,  var is much like java declaration, but val is little different.  We cannot change the reference to point to another reference, once the variable is declared using val. The variable defined using var keywords are mutable and can be changed any number of times.

Q21. What Is The Use Of Tuples In Scala?

Scala tuples combine a fixed number of items together so that they can be passed around as whole. A tuple is immutable and can hold objects with different types, unlike an array or list.

Q22. 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.

Q23. 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.

Q24. What Is Recursion Tail In Scala?

‘Recursion’ is a function that calls itself. A function that calls itself, for example, a function ‘A’ calls function ‘B’, which calls the function ‘C’.  It is a technique used frequently in functional programming.  In order for a tail recursive, the call back to the function must be the last function to be performed.

Q25. 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.

Q26. Which Ides Support Play And Scala-based Applications Development And How?

The following two popular IDEs support Play and Scala-Based Applications Development:

  • IntelliJ IDEA
  • Eclipse IDE

They support by using Scala Plugins like Eclipse IDE has a Scala IDE for Eclipse to support Play and Scala-Based Applications Development.

IntelliJ IDEA has a plug-in like “Scala Plugin for IntelliJ IDEA” to support “Scala, SBT and Play 2 Framework” based applications.

Q27. How Do You Prove That By Default, Case Object Is Serializable And Normal Object Is Not?

Yes, By Default, Case Object is Serializable. But normal object is not. We can prove this by using isInstanaceOf method as shown below:

scala> object MyNormalObject
defined object MyNormalObject

scala> MyNormalObject.isInstanceOf[Serializable]
res0: Boolean = false

scala> case object MyCaseObject
defined object MyCaseObject

scala> MyCaseObject.isInstanceOf[Serializable]
res1: Boolean = true

Q28. 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.

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
}

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.

Q29. What Is The Best Language To Use With Play Framework: Scala Or Java?

Play 2 is completely written in Scala. If we use Java with Play framework, we need to face many issues because Java does not support full FP features.

Scala is the best option to use with Play framework to develop Highly Scalable, Better Performance with Concurrency/Parallelism and Low latency applications, because:

  • Play 2 is completely written in Scala.
  • It supports full FP features.
  • It is more expression language than Java.
  • It supports Akka Actor model very easily
  • It supports some new OOP feature like Traits.
  • Play’s built-in templates are developed in Scala

Q30. When Can You Use Traits?

There is no specific rule when you can use traits, but there is a guideline which you can consider.

  • If the behaviour will not be reused, then make it a concrete class. Anyhow it is not a reusable behaviour.
  • In order to inherit from it in Java code, an abstract class can be used.
  • If efficiency is a priority then lean towards using a class
  • Make it a trait if it might be reused in multiple and unrelated classes. In different parts of the class hierarchy only traits can be mixed into different parts.
  • You can use abstract class, if you want to distribute it in compiled form and expects outside groups to write classes inheriting from it.

Q31. What Is The Default Unit And Functional Testing Framework For Play? What Is The Default Build Tool For Play? What Is The Default Template Engine For Play? What Is The Built-in Web Server Available In

Play Framework’s default Unit and Functional Testing Framework is Spec@It is very easy to test Play/Scala based applications using Spec2 Framework.

Play Framework’s Default built-in template is “Twirl”. It was developed in Scala. By using these templates, we can develop Play/Scala based applications very easily.

The Built-in or Default Web Server available for Play Framework is Netty Server.

Q32. What Are The Scala Variables?

Values and variables are two shapes that come in Scala. A value variable is constant and cannot be changed once assigned.  It is immutable, while a regular variable, on the other hand, is mutable, and you can change the value.

The two types of variables are

var  myVar : Int=0;
val   myVal: Int=1;

Q33. 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

Q34. What Are The Popular Mvc Frameworks For Scala Language To Develop Web Applications?

The following are the most popular MVC frameworks available for Scala Language to develop Web Applications:

  • Play Framework
  • Scalatra Framework
  • Spray Framework
  • Lift Framework

Q35. What Is The Best Code-coverage Tool Available For Play And Scala Based Applications?

SCoverage is the Code-coverage tool for Play and Scala based applications.

SCoverage stands for Scala Code-coverage tool. It has three separate plug-ins to supports the following build tools:

  • SBT
  • Maven
  • Gradle

Q36. Popular Clients Who Are Using Play And Scala To Develop Their Applications?

Thousands of clients are using Play and Scala in Production. The following list is the more popular clients who are using Play and Scala actively.

  • LinkedIn
  • The Guardian
  • Ocado
  • LuchidChart
  • GOV.UK

Q37. 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

Q38. What Are The Available Unit Testing, Functional Testing And/or Bdd Frameworks For Play And Scala Based Applications?

The following are most popular available Unit Testing, Functional Testing and/or BDD Frameworks for Play/Scala Based applications:

  • Spec2
  • ScalaTest
  • ScalaCheck
  • Mokito

Q39. What Is The Advantage Of Scala?

  • Less error prone functional style
  • High maintainability and productivity
  • High scalability
  • High testability
  • Provides features of concurrent programming

Q40. 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.

Q41. What Are Option, Some And None In Scala?

‘Option’ is a Scala generic type that can either be ‘some’ generic value or none.  ‘Queue’ often uses it to represent primitives that may be null.

Q42. 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

Q43. What Is The Best Scala Style Checker Tool Available For Play And Scala Based Applications?

Like Checkstyle for Java-Based Applications, Scalastyle is best Scala style checker tool available for Play and Scala based applications.

Scalastyle observes our Scala source code and indicates potential problems with it. It has three separate plug-ins to supports the following build tools:

  • SBT
  • Maven
  • Gradle

It has two separate plug-ins to supports the following two IDEs:

  • IntelliJ IDEA
  • Eclipse IDE

Q44. 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.

Q45. 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.

Q46. Mention The Difference Between An Object And A Class ?

A class is a definition for a description.  It defines a type in terms of methods and composition of other types.  A class is a blueprint of the object. While, an object is a singleton, an instance of a class which is unique. An anonymous class is created for every object in the code, it inherits from whatever classes you declared object to implement.

Q47. 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)

Q48. How Scala Solves Inheritance Diamond Problem Automatically And Easily Than Java 8?

If we use Java 8’s Interface with Default methods, we will get Inheritance Diamond Problem. Developer has to solve it manually in Java @It does not provide default or automatic resolution for this problem.

In Scala, we will get same problem with Traits but Scala is very clever and solves Inheritance Diamond Problem automatically using Class Linearization concept.

Q49. 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
  • We can pass a Function Literal to another function/method
  • We can return a Function Literal as another function/method result/return value.

Q50. 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(val firstName: String, val middleName: String, val lastName: String) 
        = new Person(firstName,middleName,lastName)
 
  def apply(val firstName: String, val 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”)