Top Scala Interview Questions and Answers

Last updated on Feb 18 2022
Rajnikanth S

Table of Contents

Top Scala Interview Questions and Answers

What is a Scala Map?

Scala Map is a collection of key value pairs wherein the value in a map can be retrieved using the key. Values in a Scala Map are not unique but the keys are 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.

What is the advantage of companion objects in Scala?

Classes in Scala programming language do not have static methods or variables but rather they have what is known as a Singleton object or Companion object. The companion objects in turn are compiled to classes which have static methods.

A singleton object in Scala is declared using the keyword object as shown below –

object Main {

def sayHello () {

println (“Hello!”);

}

}

In the above code snippet, Main is a singleton object and the method sayHello can be invoked using the following line of code –

Main. SayHello ();

If a singleton object has the same name as that of the class then it is known as a Companion object and it should be defined in the same source file as that of the class.

class Main {

def sayHelloWorld() {

println(“Hello World”);

}

}

 

object Main {

def sayHello() {

println(“Hello!”);

}

}

Advantages of Companion Objects in Scala

  • Companion objects are beneficial for encapsulating things and they act as a bridge for writing functional and object-oriented programming code.
  • Using companion objects, the Scala programming code can be kept more concise as the static keyword need not be added to each and every attribute.
  • Companion objects provide a clear separation between static and non-static methods in a class because everything that is located inside a companion object is not a part of the class’s runtime objects but is available from a static context and vice versa.

What is Option in Scala? Why would you use it?

It is used for representing whether a value is present or absent. Option collections can be used for wrapping missing values. It can also be seen as replacement for returning null values, which can be very helpful for reducing the occurrence of NullPointerException. The Option type itself is unimplemented but depends on two sub types: Some and None.

ss1

One more example to describe functionality of Option type is to use it as a method return type, which tells the caller that the method can return a string or it can return none.

ss2

Which Scala library is used for functional programming?

Scalaz library has purely functional data structures that complement the standard Scala library. It has pre-defined set of foundational type classes like Monad, Functor, etc.

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

Unit is a subtype of scala.anyval and is nothing but Scala equivalent of Java void that provides the Scala with an abstraction of the java platform. Empty tuple i.e. () in Scala is a term that represents unit value.

What is the difference between concurrency and parallelism?

People often confuse with the terms concurrency and parallelism. When several computations execute sequentially during overlapping time periods it is referred to as concurrency whereas when processes are executed simultaneously it is known as parallelism. Parallel collection, Futures and Async library are examples of achieving parallelism in Scala.

What is the advantage of using Scala over other functional programming languages? 

  • As the name itself indicates Scala meaning Scalable Language, its high scalable, maintainability, productivity and testability features make it advantageous to use Scala.
  • Singleton and Companion Objects in Scala provide a cleaner solution unlike static in other JVM languages like Java.
  • It eliminates the need for having a ternary operator as if blocks’, ‘for-yield loops’, and ‘code’ in braces return a value in Scala.

What is a Monad in Scala?

The simplest way to define a monad is to relate it to a wrapper. Any class object is taken wrapped with a monad in Scala. Just like you wrap any gift or present into a shiny wrapper with ribbons to make them look attractive, Monads in Scala are used to wrap objects and provide two important operations –

  • Identity through “unit” in Scala
  • Bind through “flatMap” in Scala

Differentiate between Val and var in Scala.

Val and var are the two keywords used to define variables in Scala. Var keyword is just similar to variable declaration in Java whereas Val is little different. Once a variable is declared using Val the reference cannot be changed to point to another reference. This functionality of Val keyword in Scala can be related to the functionality of java final keyword. To simplify it, Val refers to immutable declaration of a variable whereas var refers to mutable declaration of a variable in Scala.

What do you understand by a closure in Scala?

Closure is a function in Scala where the return value of the function depends on the value of one or more variables that have been declared outside the function.

What is Scala Future? How it differs from java.util.concurrent.Future?

Scala Future is a monadic collection, which starts a background task. It is an object which holds the potential value or future value, which would be available after the task is completed. It also provides various operations to further chain the operations or to extract the value. Future also provides various call-back functions like onComplete, OnFailure, onSuccess to name a few, which makes Future a complete concurrent task class. The main and foremost difference between Scala’s Future and Java’s Future class is that the later does not provide promises/callbacks operations. The only way to retrieve the result is Future.get () in Java.

What’s the difference ‘Nil’, ‘Null’, ‘None’ and ’Nothing’ in Scala?

  • Null – It’s a sub-type of AnyRef type in Scala Types hierarchy. As Scala runs on JVM, it uses NULL to provide the compatibility with Java null keyword, or in Scala terms, to provide type for null keyword, Null type exists. It represents the absence of type information for complex types that are inherited from AnyRef.
  • Nothing – It’s a sub-type of all the types exists in Scala Types hierarchy. It helps in providing the return type for the operations that can affect a normal program’s flow. It can only be used as a type, as instantiation of nothing cannot be done. It incorporates all types under AnyRef and AnyVal. Nothing is usually used as a return type for methods that have abnormal termination and result in an exception.
  • Nil – It’s a handy way of initializing an empty list since, Nil, is an object, which extends List [Nothing].
  • None – In programming, there are many circumstances, where we unexpectedly received null for the methods we call. In java these are handled using try/catch or left unattended causing errors in the program. Scala provides a very graceful way of handling those situations. In cases, where you don’t know, if you would be able to return a value as expected, we can use Option [T]. It is an abstract class, with just two sub-classes, Some [T] and none. With this, we can tell users that, the method might return a T of type Some [T] or it might return none.

What is a Scala Trait?

A trait is a special kind of Class that enables the use of multiple inheritance. Although a trait can extend only one class, but a class can have multiple traits. However, unlike classes, traits cannot be instantiated.

When do you use Scala Traits?

Traits are mostly used, when we require dependency injection. Unlike Java, through Spring framework, dependency injection is achieved through annotations. In Scala, there are no annotations or no special package to be imported. We just need to initialize the class with the trait and done, dependency is injected.

What are the considerations you need to have when using Scala streams?

Streams in Scala are a type of lazy collection, which are created using starting element and then recursively generated using those elements. Streams are like a List, except that, elements are added only when they are accessed, hence “lazy”. Since streams are lazy in terms of adding elements, they can be unbounded also, and once the elements are added, they are cached. Since Streams can be unbounded, and all the values are computed at the time of access, programmers need to be careful on using methods which are not transformers, as it may result in java.lang.OutOfMemoryErrors.

stream.max

stream.size

stream.sum

What do you understand by diamond problem and how does Scala resolve this?

Multiple inheritance problem is referred to as the Deadly diamond problem or diamond problem. The inability to decide on which implementation of the method to choose is referred to as the Diamond Problem in Scala. Suppose say classes B and C both inherit from class A, while class D inherits from both class B and C. Now while implementing multiple inheritance if B and C override some method from class A, there is a confusion and dilemma always on which implementation D should inherit. This is what is referred to as diamond problem. Scala resolves diamond problem through the concept of Traits and class linearization rules.

What is tail-recursion in Scala?

There are several situations where programmers have to write functions that are recursive in nature. The main problem with recursive functions is that, it may eat up all the allocated stack space. To overcome this situation, Scala compiler provides a mechanism “tail recursion” to optimize these recursive functions so that it does not create new stack space, instead uses the current function stack space. To qualify for this, annotation “@annotation.tailrec” has to be used before defining the function and recursive call has to be the last statement, then only the function will compile otherwise, it will give an error.

What do you understand by Implicit Parameter?

Wherever, we require that function could be invoked without passing all the parameters, we use implicit parameter. We provide the default values for all the parameters or parameters which we want to be used as implicit. When the function is invoked without passing the implicit parameters, local value of that parameter is used. We need to use implicit keyword to make a value, function parameter or variable as implicit.

How does yield work in Scala?

The yield keyword if specified before the expression, the value returned from every expression, will be returned as the collection. The yield keyword is very useful, when there is a need, you want to use the return value of expression.  The collection returned can be used the normal collection and iterate over in another loop.

ss3

What do you understand by a case class in Scala?

Case classes are standard classes declared with a special modifier case. Case classes export their constructor parameters and provide a recursive decomposition mechanism through pattern matching. The constructor parameters of case classes are treated as public values and can be accessed directly. For a case class, companion objects and its associated method also get generated automatically. All the methods in the class, as well, methods in the companion objects are generated based on the parameter list. The only advantage of Case class is that it automatically generates the methods from the parameter list.

Features of Case Class in Scala

  • Case objects and Case class are serializable by default.
  • Case classes can be used for pattern matching.

What is the use of Auxiliary Constructors in Scala?

Auxiliary Constructor is the secondary constructor in Scala declared using the keywords “this” and “def”. The main purpose of using auxiliary constructors is to overload constructors. Just like in Java, we can provide implementation for different kinds of constructors so that the right one is invoked based on the requirements. Every auxiliary constructor in Scala should differ in the number of parameters or in data types.

Differentiate between Array and List in Scala.

  • List is an immutable recursive data structure whilst array is a sequential mutable data structure.
  • Lists are covariant whilst array are invariants.
  • The size of a list automatically increases or decreases based on the operations that are performed on it i.e. a list in Scala is a variable-sized data structure whilst an array is fixed size data structure.

What do you understand by apply and unapply methods in Scala?

apply and unapply methods in Scala are used for mapping and unmapping data between form and model data.

Apply method – Used to assemble an object from its components. For example, if we want to create an Employee object  then use the two components  firstName and lastName and compose the Employee object using the apply method.

Unapply method – Used to decompose an object from its components. It follows the reverse process of apply method. So if you have an employee object, it can be decomposed into two components- firstName and lastName.

What are the four types of scala identifiers?

The four types of identifiers are

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

What are the different types of Scala literals?

The different types of literals in scala are

  • Integer literals
  • Floating point literals
  • Boolean literals
  • Symbol literals
  • Character literals
  • String literals
  • Multi-Line strings

Where is Scala usually used?

As a general-purpose language, Scala has varied uses. Typically, Scala can be used for writing codes for extensive analytics or machine learning engines. As a type-safe programming language that can be compiled with Java Virtual Machine, Scala’s primary use is to upgrade the existing Java codes, which are often complicated and tedious into prompt and precise codes. This has found widespread applications in popular platforms like Twitter, LinkedIn, and even Netflix.

What are some of the major frameworks of Scala?

In Scala, the multi-paradigm compatibility is a unique feature. Scala’s frameworks range from Akka framework, Spark framework, Play framework, Scalding framework, and Neo4j framework to lift framework and bowler framework.

What is a closure in Scala?

A closure in Scala is a function whose value depends on variables declared outside of it. Let’s take an example.

scala> var c=5

c: Int = 5

scala> val mul2=(a:Int,b:Int)=>(a+b)*c

mul2: (Int, Int) => Int = $$Lambda$1533/239864031@6d90e705

scala> mul2(2,3)

res45: Int = 25

scala> c=7

c: Int = 7

scala> mul2(2,3)

res46: Int = 35

In this example, mul2 reads the new value of ‘c’ when we call it a second time.

What is function currying in Scala?

Currying is the technique of transforming a function that takes multiple arguments into a function that takes a single argument Many of the same techniques as language like Haskell and LISP are supported by Scala. Function currying is one of the least used and misunderstood one.

Can a companion object in Scala access the private members of its companion class in Scala?

According to the private access specifier, private members can be accessed only within that class but Scala’s companion object and class provide special access to private members. A companion object can access all the private members of a companion class. Similarly, a companion class can access all the private members of companion objects.

What is the advantage of having immutability in design for Scala programming language?

Scala uses immutability by default in most of the cases as it helps resolve issues when dealing with concurrent programs and any other equality issues.

What is the use of Scala’s App?

App is a trait defined in scala package as “scala.App” which defines the main method. If an object or class extends this trait then they will become Scala executable programs automatically as they inherit the main method from application. Developers need not write main method when using App but the only drawback of using App is that developers have to use same name args to refer command line arguments because scala.App’s main() method uses this name.

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

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

 Mention the types of Variables in Scala? And What is the difference between them?

The Variables in Scala are mainly of two types:

Mutable Variables

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

Immutable Variables

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

 

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.

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 

Explain the Operators in Scala

The following are the Operators in Scala:

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

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.

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.

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.

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.

1

2

3

object Tecklearn extends App{

println(“Hello World”)

}

What are Higher-order functions?

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.

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.

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.

Example:

1 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

Explain Traits in Scala.

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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()

}

}

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

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

1

2

3

4

5

6

7

8

9

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)

}

}

 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.

1

2

3

4

5

6

//Syntax:

object {

implicit class Data type) {

def Unit = xyz

}

}

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.

1

2

3

4

5

6

7

8

9

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.

 

1

2

3

4

5

6

7

8

9

10

11

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

1

2

3

4

5

6

7

8

9

class Outer {

class Inner {

def f() { println(“f”) }

class InnerMost {

f() // OK

}

}

(new Inner).f() // OK because now f() is public

}

How is Scala is both an OOP and Functional Programming Language?

Scala is a Java-based multiparadigm programming language that treats each value as an ‘object’ that further includes ‘functions.’ This is what makes Scale a combination of both OOP and functional programming languages.

What is a Monad in Scala?

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.

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.

1

2

3

4

//Syntax

(z:Int, y:Int)=> z*y

Or

(_:Int)*(_Int)

 

How do I Append data in a list?

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

1

2

3

use “:+” single value

var myList = List.empty[String]

myList :+= “a”

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.

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.
  • PreDefPredef provides type aliases for types which are commonly used, such as the immutable collection types Map, Set, and the List constructors

Why is an Option used in Scala?

 Option in Scala is used to Wrap the Missing value.

Mention the Identifiers in Scala.

There are four types of Scala Identifiers:

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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

//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()

}

}

 How do you define a function in Scala?

 def keyword is used to define the Function in Scala.

1

2

3

4

5

6

7

object add {

def addInt( a:Int, b:Int ) : Int = {

var sum:Int = 0

sum = a + b

return sum

}

}

 

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.

ss4

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.

1 for (i <- 1 to 5) yield i

 Differentiate between Null, Nil, None and Nothing

They appear similar but different in their behaviour:

ss5

Explain If-Else-If terminology

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

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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”);

}

}

}

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.

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.

1

2

3

4

5

6

7

8

9

object Demo {

def main(args: Array[String]) {

var a = 10;

//An infinite loop.

while( true ){

println( “Value of a: ” + a );

}

}

}

What is the Syntax for function declaration in Scala?

The Syntax for function declaration is as follows:

1

2

3

4

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.

How do I Concatenate two Strings?

 There are three methods to perform string concatenation in Scala

1

2

3

string1.concat(string2);

“My name is “.concat(“Zara”);

“Hello,” + ” world” + “!”

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.

Explain how to create Arrays

We use the following methods to create arrays in Scala:

    • We use ofDim to declare multidimensional arrays.
1 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]
1 range (10, 20, 2)

What is Map in Scala?

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

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

 

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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”)

}

}

}

}

Explain Pattern Matching in Scala through an example

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.

1

2

3

4

5

6

7

8

9

10

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”

}

}

 

Explain Extractors in Scala

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.

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

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.

Explain recursion through a program

1

2

3

4

5

6

7

8

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

 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

 

1

2

import scala.collection.mutable.Queue

val empty = new Queue[Int]

Define Scala?

Scala is a Java-based Hybrid programming language. It combines the features of functional-oriented and object-oriented programming language. It is used by integration with the Java Virtual machine and can compile the written code.

How is Scala a programming language with a combination of both functional and object-oriented programming?

Scala programming language treats every single value as an object, which also includes Functions. This way, it is a combination of both functional and object-oriented programming.

What are the frameworks supported by Scala?

There are various frameworks supported by Scala that include the following.

  1. Spark Framework
  2. Play Framework
  3. Akka Framework
  4. Neo4j Framework
  5. Bowler Framework
  6. Scalding Framework
  7. Lift Framework

ss6

What are the different kinds of variables in Scala?

 There are mainly two types of variables in Scala, which include Mutable variables and Immutable Variables.

Define the features of Mutable Variables?

The Mutable variables can be declared by using the var keyword. The values in these variables support changes.

Define the features of Immutable Variables?

The Immutable Variables can be declared by using the val keyword. The values in these variables do not support changes.

Define Stream in Scala?

 A stream is defined as a Lazy list, which helps in the evaluation of the elements only when they are needed.

What is the benefit of Streams in Scala?

The benefit of Streams in Scala is that it helps in enhancing the performance of the program.

What are the advantages of Scala?

There are several advantages of Scala, which include the following.

  1. Scalable
  2. Maintainable
  3. Productive
  4. Concurrent programming
  5. Consists of Native Tuples codes Consists of Testable codes
  6. Concise code
  7. No Boilerplate code
  8. Singleton objects are clearer in the solution than static

. What are the different operators in Scala?

 The different operators in Scala include the following.

  1. Assignment operators
  2. Relational operators
  3. Logical operators
  4. Arithmetic operators
  5. Bitwise operators

What is Recursion in Scala?

Recursion is referred to as the function in Scala that calls itself.

Give an example of Recursion in Scala?

 When Function A calls function B, which further calls function C, then it is called recursion in Scala and is mostly used in Functional Programming.

What is Tail Recursive?

Tail recursive is a call back to the function that should be the end task function that is to be performed.

What are Tuples in Scala?

 Tuples in Scala combine the finite numbers of items all together so that the programmer can Pass tuple around as a whole.

How do I Append data in a list?

 To append data in a list, you should use “:+”. This appends a single value to the list. For example:

var a = List.empty[String]
a: List[String] = List()
a:+=”pear”

If you want to add a list to another, then use “++” as follows:

a++ = List(“mango”,”banana”)

 

Explain the Syntax for function declaration in Scala?

 The syntax is:

def functionName(parameters : typeofparameters) : returntypeoffunction = {
// function statements
}

Note that the keyword return is not used. Scala determines the return type by seeing the last parameter. A function is created using the ‘def’ keyword. All the parameters and their return types are mentioned clearly. The equal operator, when added, returns the value, else if no equal operator is used, the function will not return any value.

How to create Arrays in Scala?

To create an array, we have to declare a variable that references the array and specify the type of array. An array can be created as:

var z:Array[String] = new Array[String](10)
or
var z = new Array[Int](5)

Describe Exception Handling in Scala?

 Exception handling in Scala is similar to Java except that there are no checked exceptions. To throw exceptions, we use throw new <ExceptionName> and to catch we can use try{}catch{}blocks. There is also a finally block which is executed at the end. We can catch multiple exceptions inside the catch block using case ex: blocks. Example:

try {
val input = new FileReader(“myinput.txt”)
} catch {
case ex: FileNotFoundException => {
println(“File not found”)
}
case ex: IOException => {
println(“Exception in I/O”)
}
} finally {
println(“Exiting the code…”)
}
}

What is a ‘Scala set’? What are methods through which operation can be performed on sets?

 Set is a collection that has unique elements (no duplicates). There are two types of sets: mutable and immutable (its value cannot be changed). By default, Scala uses immutable sets. Few methods for set operations are:

  • head: returns the head (first element) of the set
  • tail: returns entire set except the head element
  • isEmpty: checks if the set is empty, returns Boolean

Explain the ways Scala is better than other programming languages?

 A few reasons are:

  • Though it is object-oriented, Scala has features of a functional programming language as well.
  • It is concise, easy to code, readable, easy to compile and error-free.
  • Deploys concurrency thus making synchronization easy.
  • Third-party libraries can be added easily in the form of language constructs.
  • Works in a multicore architecture environment.

Explain the difference between var and value?

 Both var and value are used for declaring variables. However, var represents a variable whose value can be updated later in the code, whereas val (value) is like a constant or final value which cannot be changed. Once a var or val is assigned a value, its type cannot be changed. Example:

var var1 = new A(6);
var1 = new A(7);
val value = 6;
value = 7; // This will not work

Mention the different types of Scala literals?

There are many literals in Scala:

  • Integer literals: Int or Long, example, 12, 0999L
  • Floating-point literal: Float, example, 1.3
  • Boolean literals: true/false
  • Symbol literals: interned strings, example ‘WHO
  • Character literals: single character, example: ‘v’, ‘\t’
  • String literals: sequence of characters, for example, “Hi, how are you?”

What is exception propagation in Scala?

 An exception can be thrown in Scala using the . clause and propagated to the next class. It is the same as other programming languages like Java. Example:

try{
var fr = new FileReader(“data.txt”)
}catch {
case ex: FileNotFoundException =>{
println(“file not found”)
}
case ex: IOException => {
println(“IO Exception”)
}
}

What are the different scopes for variables in Scala?

 There are three different scopes for variables in Scala, which include Fields, Method Parameters, and Local Variables.

What are Fields in Scala?

Fields are variables that are declared inside an object. They can be accessed from any point inside the program, depending upon the access modifiers. It can be declared using val or var.

What are the method parameters?

Method parameters are Pass values to the methods. They are strictly immutable and can be accessed from inside a method. However, the use of Reference can be made for accessing them from outside the method provided.

What are the local variables?

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

What is a closure in Scala?

The closure is a function in Scala whose return value is dependent on the value of one or more variables that are declared outside the closure.

Define Traits in Scala?

Traits in Scala is a unit that encapsulates the method and its variables or field.

What is the difference between Scala and Java?

 The difference between Scala and Java includes the following.

ss8

What is an extend keyword in Scala?

An extend keyword in Scala helps in extending a base Scala class so that you can design an inherited class just like it is done in Java by use of extending keywords.

What are the restrictions in extend key keywords in Scala?

In Scala, there are two restrictions to extend keywords. This includes the first one as method overriding, which requires override keywords and the second one as a primary constructor that can pass parameters to the base constructor.

Define Implicit classes with syntax in Scala?

Implicit classes with syntax in Scala supports the implicit conversation with the class’s primary constructor when the class is in scope. It is marked with the “implicit” keyword and introduced in Scala 2.10 version.

What are the different types of Access Modifiers available in Scala?

  There are three types of Access Modifiers available in Scala, which include Private, Public, and Protected.

What is a Private Access Modifier?

A Private Access Modifier supports the restriction of the accessibility of a private member to the class or object as a set or declared in advance.

What is Public Access Modifier?

Public Access Modifier does not require any explicit modifier to allow the public members to get access, and the members can access from anywhere.

What is Protected Access Modifier?

A Protected Access Modifier supports accessibility only from the subclass of the class where the member is defined and authorized.

Define Monad in Scala?

Monad in Scala is an object. It helps in wrapping another object as per the mini-program, which can be a function to perform data manipulation, particularly on the underlying object. It indirectly manipulates the object and chooses the method to apply for the program on the underlying object.

What is Scala Anonymous Function?

Scala Anonymous Function is also known as Function Literals’ in the Source Code. During the run time, these function literals are instantiated into objects, which are known as Function values, which provides a relatively easy Syntax for defining these Anonymous functions.

Why is Immutability preferred in Scala?

Immutability is preferred in Scala because it supports the design and uses it as a default. It helps in dealing with the Concurrent programs as well as Equality issues.

Define different packages in Scala?

There are three different packages in Scala. These are,

  1. Java.lang._: It is a package that provides classes that are fundamental for the design of the Java programming language.
  2. Java.io._: It is a package that imports every class in Scala for input-output resources.
  3. PreDef: It offers type aliases for types that are used regularly used in Scala. These include Safe, Map, and the List constructors.

What is the role of Options in Scala?

Options have a vital role in Scala, which is to Wrap the Missing value.

Define types of Scala Identifiers?

There are four types of Scala Identifiers, which include,

  1. Literal identifiers
  2. Alphanumeric identifiers
  3. Mixed identifiers
  4. Operator identifiers

What are the procedures to compile Scala code?

The procedure to compile Scala Code starts with the writing of the Code in Scala IDE or Scala REPL, which is later converted into the Byte Code and thereby transferred to Java Virtual Machine or JVM for compilation purpose.

What are the features of Yield in Scala?

Yield has several features as,

  1. It is used as a Loop.
  2. It produced value for each iteration.
  3. It supports the use of Map, FlatMap, and Filters along with nomads.

Define Null, Nill, None, and Nothing in Scala?

 Null, Nill, None, and Nothing in Scala can be defined as follows.

  1. Null denotes the absence of a value.
  2. Nil represents the end of a List.
  3. None is the value of an option that has no value.
  4. Nothing is the lowest type in the type system.

What are the different Loops in Scala?

 There are three different types of Loops in Scala.

  1. While Loop helps in repeating the statement or group of the statement when the condition comes out to be true, this way, it tests the conditions before the execution of the Loop body.
  2. Do-While helps in testing the condition at the end of the Loop body.
  3. For, helps in executing a sequence of statement number of times and abbreviates the code that manages in the Loop variable.
  4. Break acts as a Loop control statement that terminates the Loop statement and transfers the execution to the statement that soon follows the Loop.

What is an Infinite Loop?

An Infinite Loop appears when a condition never becomes a false statement.

What are the different String Methods?

There are five different String Methods which include,

String trim(): It returns the copy of the string with leading and trailing of the whitespace omitted.

  1. String to Uppercase: It converts all of the features in the String to the Uppercase using the given Locale rules.
  2. Char[] to CharArray(): It converts the string to a new character array.
  3. String[] split(String regext): It splits the string around the matches of the given regular expression.
  4. Int length(): It returns the length of the string.

Define Map in Scala?

A Map in Scala is the collection of key or value pairs that helps in retrieving a Value-Based on its key.

What is Pattern Matching in Scala?

Pattern Matching in Scala consists of various sequences of alternatives that start with the Keyword case. Each of the alternatives available uses Pattern and Expressions. Scala evaluates these Patterns when they match, and the arrow symbol “=>” is used to separate it from the expressions.

What is an Extractor in Scala?

 An Extractor in Scala is referred to as the Object. It applies a method called “Unapply” on its members for the purpose of matching the value and take it apart.

Define Auxiliary constructor and Que?

An auxiliary constructor is used for Constructor Overloading. It needs to call either previously defined or primary constructor in the first line of its body.

A queue is a data structure that is just like the Stack. However, its additional feature is that it follows First In First Out procedures for data processing. To apply Queues, you need to import a library called import scala.

Collection.mutable.Queue.

Explain Why Scala is Hybrid Language?

Scala fuses the features of both functional and object-oriented programming languages.  Every value that is input in Scala is treated as an object. Concomitantly, every function is a value. Hence, Scala facilitates every function to be an object. This makes Scala a hybrid programming language.

What are the significant advantages of Scala, in comparison to the existing programming languages?

Scala’s very inception was to upgrade the current cohort of programming languages and add incremental value to popular programming languages like Java, Python, C programming, etc. So, at the very outset, Scala brings in shorter, concise codes that have flexible syntax.

Further, unlike other statically typed programming languages, Scala does not require additional information. For instance, one need not specify the type or have to repeat it at any different stage of the code writing. Scala is integrated into Java Virtual Machine so it can compile any existing codes in Java, so it enables the reuse of codes.

By virtue of being a hybrid programming language, Scala also supports concurrent programming. Moreover, Scala flags out errors in the codes immediately, so it supports enhanced testing. Overall, it ensures high performance and high productivity.

What are the different types of Variables in Scala?

There are two types of Variables in Scala:

  • Mutable Variables – These Variables have values that support changes (new values can be assigned to them after their creation). They are declared using the ‘var’ keyword.
  • Immutable Variables – These Variables have values that cannot be changed once created. They are declared using the ‘val’ keyword.\

Mention a few frameworks supported by Scala.

The frameworks supported by Scala are:

  • Spark
  • Scalding
  • Neo4j
  • Play
  • Akka
  • Lift

What is Recursion Tail?

In Scala, there’s a function known as Recursion Tail that is capable of calling itself. For instance, function a can call function that further calls function c. To create a recursive tail, the call back function must be the last performed function.

What purpose do Tuples serve in Scala?

A Tuple’s purpose is to combine a fixed and finite number of items together to allow the programmer/coder to pass a tuple as a whole. Tuples can hold objects with varying data types and are immutable.

Tuples represent the combination of finite inputs. Tuples are used to combine a fixed number of items together. This enables the programmer to integrate discreet items into a whole. Tuples are immutable but can combine items of different types together.

What is a BitSet?

A BitSet is a set consisting of non-negative integers depicted as arrays. The arrays vary in size but are compressed into 64-bit words. In a BitSet, the largest number becomes its memory footprint.

What is ofDim()?

In Scala, ofDim() is a function that allows you to create multidimensional arrays. You can store the data in multiple dimensions – it becomes like a matrix of sorts.

What is the purpose of Closure function?

The closure is a function in Scala whose return value relies on the value of one or more variables that have been declared outside the closure function.

What is the need for App in Scala?

Before we explain why we need an App in Scala, let’s understand what a Scala Trait is. A Scala trait is a unit of Scala which facilitates multiple inheritances, especially of methods and variables or fields. The app is a type of Scala Trait.

Just as a class combines data and methods in Scala, an App integrates the main method and its members. In many ways, an App may be categorized as a helper class. Through the App in Scala, we can turn objects into executable codes.

What are the general access modifiers in Scala?

Private, Protected and Public are the major three access modifiers available in Scala. Each of them has certain salient features.

The private access modifier limits the access of a user to only the class or the object where the user is defined.

The protected member may access any Subclass of a Class where the user is defined.

Unlike the former two, Public members can be accessed from anywhere in the program. Any pre-defined keywords do not restrict access.

What are the types of scopes provided for variables in Scala?

Scala has three scopes for variables according to the use case:

Fields – These are variables that are declared within an object. Depending upon the access modifiers, fields can be accessed anywhere inside the program. They can be declared both as ‘var’ and ‘val.’

Method Parameters – These are immutable variables that are primarily used to pass values to methods. They can be accessed within a method. However, you can also access method parameters from outside the method using a Reference.

Local Variables – These variables are declared within a method, and they can be accessed only from inside a method.

How can you run a Scala program?

In order to run a program using Scala, we need first to write it using SCALA REPL and then proceed to compile it. This can be done using the ‘SCALAC’ command to convert it into a Byte code and then transferred to the Java Virtual Machine. Following that, the ‘SCALA’ command can be used to run the program.

Explain the difference between the terms “Null,” “Nil,” “None,” and “Nothing.”

Although these terms sound similar, each represents something different.

Null denotes the absence of a value, more particularly the absence of type information for complex types inherited from AnyRef.

Nil refers to the end of a List.

None denotes the value of an option that has no value inside it.

Nothing represents the lowest type – all values under AnyRef and AnyVal fall under it.

What are the different types of loops in Scala?

Loops are the most common array strings used in Scala. Scala provides four main types of loops:

While Loop- Using a while loop in Scala, users can repeat a statement as long as the condition defined by the “if-else” command holds true. The while loop first tests the condition and then executes it. It comes handy in defining infinite loops. In this case, the condition is set in a way that it doesn’t become false ever.

Do-While Loop- This loop functions similar to a while loop, with the only exception that the condition is tested at the end of the body of the loop.

For loop-It executes a sequence of statements in a loop body multiple time. For loop is effective in abbreviating the code that manages the loop variable in such cases.

Break- Unlike the former three, break command is used to terminate a loop immediately after a statement and move it to the execution of the loop.

What are the Presidency and Priority tables in Scala?

The presidency and priority tables determine which operations are to be performed first in Scala.  The following table lays down the operator precedence in Scala.

For instance, to get the results for p+q*r, Scala will perform the operations in the following order:

First, q*r will be calculated. Then, the value for(q*r) will be added to p to get the final output.

What are the predominant operators in Scala?

Some of the major operators in Scala are Arithmetic operators, Relational operators, Logical operators, Bitwise Operators, and Assignment Operators. The operators in Scala are also referred to as identifiers.

How does a class differ from an object in Scala?

Simply put, an object resides within a class in Scala. A class in Scala combines data and its methods while an object is an instance inside a given class.

What is a Trait? When is it used?

A Trait denotes a particular unit of Class that facilitates the use of multiple inheritances. It encapsulates a method along with its variables and fields. While a Trait can extend only one Class, a Class can have multiple traits.

Traits are primarily used for dependency injection. Contrary to Java where dependency injection is accomplished through annotations, Scala has no annotations or no special package that needs to be imported – you only need to initialize the Class with the Trait to trigger the dependency injection.

What are the default packages in Scala?

Scala comes with three default packages, namely Java.lang, java.io, and PreDef. The functionalities of all three packages vary.

Java.lang is fundamentally a Java programming language. It includes classes that are compatible with the design of the java programming language.

Java.io helps in importing the classes in Scala for input-output resources.

PreDef includes type alias for specifically immutable collections like Map, Set, and Lists.

What is an Implicit Parameter?

Implicit Parameter allows you to invoke a function without passing all the parameters. In this case, you have to provide the default values for all the parameters or those parameters that you want to declare as implicit. To make a value/function parameter/variable ‘implicit,’ you require an implicit keyword.

How does Scala Option help?

Scala Option keyword comes handy when you’re trying to wrap a missing value.

What is a Monad?

Another fascinating feature of Scala is the ability of one object to wrap another object. This is made possible using a Monad.  A monad is an object to which functions can be directed for manipulation of the underlying objects. Monad does not apply the program to the objects directly. In the common parlance, it is analogous to a gift wrapper.

What is the Scala Map?

A Scala map refers to a collection of key-value pairs whose values have to be retrieved using a key. While the values in a map are not unique, the keys are unique.

The Scala Map is effectively the collection of the variables. It includes keys and values. The keys are used to retrieve the values. While the values are not unique in a Scala map, the keys are. Similar to the variables, a Scala map can also be mutable or immutable.

What is ofDim in Scala?

ofDim() is a method in Scala that lets us create multidimensional arrays. Since these let us store data in more than one dimension, we can store data like in a matrix. Let’s take an example.

scala> import Array.ofDim

import Array.ofDim

scala> var a=ofDim[Int](3,3)

a: Array[Array[Int]] = Array(Array(0, 0, 0), Array(0, 0, 0), Array(0, 0, 0))

scala> var k=1

k: Int = 1

scala> for(i<-0 to 2){

| for(j<-0 to 2){

| a(i)(j)={i+k}

| k+=1

| }

| k-=1

| }

scala> a

res12: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9)).

What is a BitSet?

BitSet is a collection of smaller integers represented as bits of the larger integer. We can add multiple items in a bitset using the ‘++’ operator similar to list. Bitsets can be mutable and immutable and are sets of non-negative integers.

Is Tuple immutable?

 Yes, Tuple is immutable mostly in the case of Array or List wherein it can hold objects with different datatypes.

What is Class in Scala?

Class in Scala combines the data and its methods in Scala.

What is an Object in Scala?

An object in Scala is one particular instance in a class.

Do we need App in Scala?

Yes, we do need App in Scala so that it could act as a helper class that holds the main method and its members together.

What is the benefit of App trait? Give an example?

An App trait can be used for quickly turning the objects into executable programs. For example, we can have our classes extend App with the purpose of rendering the executable code.

Define Higher-order functions?

 Higher-order functions are defined as a function that does one or more of the functions as arguments, returns a function as its result.

What do you have to say about exception propagation in Scala?

When a function experiences an exception, it looks for a handler to deal with it. When it fails to find one, it searches for one in the caller method. Failing there, it looks for yet another in the next caller in the chain. Whenever it does find a handler, it makes it catch the exception. This is exception propagation.

What is a BitSet?

A bitset is a set of non-negative integers depicted as arrays. These arrays are variable in size and packed into 64-bit words. The largest number in a bitset determines its memory footprint. Let’s take an example.

scala> import scala.collection.immutable._

import scala.collection.immutable._

scala> var nums=BitSet(7,2,4,3,1)

nums: scala.collection.immutable.BitSet = BitSet(1, 2, 3, 4, 7)

scala> nums+=9 //Adding an element

scala> nums

res14: scala.collection.immutable.BitSet = BitSet(1, 2, 3, 4, 7, 9)

scala> nums-=4 //Deleting an element

scala> nums

res16: scala.collection.immutable.BitSet = BitSet(1, 2, 3, 7, 9)

scala> nums-=0 //Deleting an element that doesn’t exist

scala> nums

res18: scala.collection.immutable.BitSet = BitSet(1, 2, 3, 7, 9)

What is a vector in Scala?

A vector is a general-purpose data structure that is immutable. We can use it when we want to hold a huge number of elements and want random access to them. This data structure extends the trait IndexedSeq and the abstract class AbstractSeq.

scala> import scala.collection.immutable._

import scala.collection.immutable._

scala> var v1=Vector.empty

v1: scala.collection.immutable.Vector[Nothing] = Vector()

scala> var v2=Vector(7,2,4,3,1)

v2: scala.collection.immutable.Vector[Int] = Vector(7, 2, 4, 3, 1)

scala> var v3:Vector[Int]=Vector(8,2,6,5,9)

v3: scala.collection.immutable.Vector[Int] = Vector(8, 2, 6, 5, 9)

scala> v3=v3 :+7 //Adding a new element

v3: scala.collection.immutable.Vector[Int] = Vector(8, 2, 6, 5, 9, 7)

scala> v2++v3 //Merging two vectors

res19: scala.collection.immutable.Vector[Int] = Vector(7, 2, 4, 3, 1, 8, 2, 6, 5, 9, 7)

scala> v3.reverse //Reversing a vector

res20: scala.collection.immutable.Vector[Int] = Vector(7, 9, 5, 6, 2, 8)

scala> v3.sorted //Sorting a vector

res21: scala.collection.immutable.Vector[Int] = Vector(2, 5, 6, 7, 8, 9)

In results 20 and 21, we do not assign the expression to any variable, so not that this doesn’t change the original vectors.

Explain streams in Scala.

A stream is a lazy list as it evaluates elements only when it needs to. This lazy computation enhances program performance.

scala> val stream=177#::199#::69#::Stream.empty

stream: scala.collection.immutable.Stream[Int] = Stream(177, ?)

Since we don’t need the second element yet, Scala doesn’t evaluate it.

scala> val stream1=(1 to 7).toStream

stream1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> stream.head

res22: Int = 177

scala> stream.map{_*2}

res24: scala.collection.immutable.Stream[Int] = Stream(354, ?)

What are the advantages of Scala?

Among various other benefits of the language, here are a few:

  • 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

Who designed Scala? Which is the latest version?

At the time of writing, Scala 2.12.6 is the latest version. The interviewer may ask you this to find out whether you keep yourself updated. Martin Odersky, a German computer scientist, began designing it in 2001 at EPFL, Switzerland.

How is Val different from var in Scala?

In this language, val is a value and var is a variable. These are two different keywords for declaring immutable and mutable entities respectively. This means that you can always reassign a var, but trying to do that to a val makes the compiler throw an error.

scala> val c=7

c: Int = 7

scala> c=8

<console>:19: error: reassignment to val

c=8

^

scala> var c=7

c: Int = 7

scala> c=8

c: Int = 8

Why do we need App in Scala?

App is a helper class that holds the main method. We can have our classes extend App to render executable code:

scala> object Hello extends App{

| println(“Hello”)

| }

defined object Hello

With this code, our object Hello inherits the main method from the App trait.

How is a class different from an object?

A class is a blueprint, a definition. In terms of methods and compositions of other types, it defines a type. An object, however, is a singleton. It is a unique instance of a class. Every object in your code has an anonymous class for it. Where in Java, you would use a class with static members, you use an object in Scala.

How do the terms ‘Null’, ‘Nil’, ‘None’, and ‘Nothing’ differ in Scala?

While they appear similar, the mentioned terms are slightly different in their behaviors. Here’s how:

  • Null represents the absence of value. It depicts the absence of type information for complex types inherited from AnyRef.
  • Nil denotes the end a List.
  • None is the value of an Option with no value in it.
  • Nothing is the lowest type in the entire type system. All values under AnyVal and AnyRef fall under this. A method that throws an exception uses Nothing as a return type.

What is a monad in Scala?

A monad is something to which we can pass functions and manipulate the underlying object’s data. We don’t need to manipulate the object directly. Hence, a monad is an object that wraps another.

Differentiate a Scala function from a Java method.

In Scala, a function is also a value. Unlike in Java, we can assign it to vals and vars, and also return it from another function. Check Higher-Order Functions in Scala. Since Java 8, we can use lambda expressions to use functions as first-class objects. So, we can pass functions to methods.

Explain vararg arguments.

With varargs, we can pass a variable number of arguments to a method.

scala> def func(arg:String*)=arg.mkString(“, “)

func: arg: String*)String

scala> func(“red”,”green”,”blue”)

res28: String = red, green, blue

What do you know about traits in Scala?

A trait is like a partially implemented interface that can hold abstract and non-abstract methods. They’re like Java interfaces; that is what Scala compiles them into. Let’s take an example.

scala> trait Hello{

| def sayhello()

| }

defined trait Hello

warning: previously defined object Hello is not a companion to trait Hello.
Companions must be defined together; you may wish to use: paste mode for this.

scala> class A extends Hello{

| def sayhello(){

| println(“Hello”)

| }

| }

defined class A

scala> var a=new A()

a: A = A@10e595ed

scala> a.sayhello()

Hello

What is an Option in Scala?

Scala Option is a kind of a container. It can hold zero or one element of a type. When it holds a value, it holds Some[T]; otherwise, it holds a None object, as we discussed in the previous question.

scala> val o:Option[Int]=Some(7)

o: Option[Int] = Some(7)

scala> val o1:Option[Int]=None

o1: Option[Int] = None

Is a case class the same as a regular class in Scala?

No, these aren’t synonyms. Here are a few important characteristics of a Scala case class:

  • They support pattern-matching
  • To create an instance of a case class, you don’t need new
  • Scala automatically generates methods like equals(), hashcode(), and toString() for case classes
  • For all constructor arguments for a case class, Scala automatically generates accessor methods

For more on case classes, read up on Case Classes in Scala.

What is tail-recursion in Scala?

Recursion is when a function makes a call to itself. When we place this call as the last action performed in the function, we can call the function tail-recursive.

scala> def factorial(n:Int):Int={

| if(n==1) return 1

| n*factorial(n-1)

| }

factorial: (n: Int)Int

scala> factorial(5)

res30: Int = 120

What is a higher-order function in Scala?

This is a feature of Scala. A higher-order function is one that takes another as a parameter, or that returns a function.

scala> def func1(s:String){

| println(“I love “+s)

| }

func1: (s: String)Unit

scala> def func2(f:String=>Unit,s:String){

| f(s)

| }

func2: (f: String => Unit, s: String)Unit

scala> func2(func1, “pizza”)

I love pizza

Explain the working of yield in Scala.

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

scala> for(i<-1 to 4) yield i*3

res35: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 6, 9, 12)

Prove that Scala is a language statically/strongly typed.

Since the compiler performs type checking at compile time instead of runtime, it lets the developer notice and resolve errors at the compile time itself. Hence, we can say that it is strongly and statically typed. Read up on type inference in Features of Scala.

How do you use Scala to append to a List?

For this purpose, we use the single value ‘:+’.

scala> var a=List.empty[String]

a: List[String] = List()

scala> a :+=”red”

scala> a :+=”green”

scala> a :+=”blue”

scala> a

res40: List[String] = List(red, green, blue)

//And now, appending a List to this

scala> a++=List(“golden”,”bronze”)

scala> a

res42: List[String] = List(red, green, blue, golden, bronze)

Are concurrency and parallelism the same thing? Explain.

When we take a task and break it into subtasks to execute at one time by multiple threads, we call it parallelism. Concurrency, however, is when multiple computations execute sequentially; this is during overlapping time periods. When we avoid access to a mutable state by multiple threads at a time, it is concurrency. Sometimes, actors can concurrent as well as parallel. Node.js is a single-threaded implementation yet is concurrent because of its event loop. An example of parallelism is parallel collections.

Explain different types of identifiers in Scala.

We have four kinds of identifiers in Scala.

  1. Alphanumeric Identifiers

These contain letters, underscores, and digits, but only begin with a letter or with an underscore. We name them in camel case. Here are a few examples: ab12, myVal, Pi.

  1. Operator Identifiers

These contain operator characters except these- ( ) [ ] { } ‘ ” _ . , ; , `. Some valid examples are: +  => <?> ::: .

  1. Mixed Identifiers

These contain an alphanumeric identifier, an underscore, and also an operator identifier. Here are some valid examples: myVar_=, unary_+.

  1. Literal Identifiers

These contain an arbitrary string enclosed in backticks(`). Some valid examples are: `class`, `Hello, World!`.

Is Scala compatible with Java? Explain.

We’ve seen that both Scala and Java work on the JVM on the backend. Well, Scala classes are Java classes and Java classes are Scala classes too. So, you can call a Java method from a Scala method, and vice-versa. You can also extend classes from one language in another. However, features like traits in Scala have no equivalents in Java.

Explain implicit parameter precedence.

The compiler doesn’t randomly look for implicits in your code; it follows the following precedence:

  • Locally declared implicits
  • Imported implicits
  • Outer scope (ex- a class for a method)
  • Inheritance
  • Package object
  • Implicit scope like companion objects

What is a lens in Scala?

A lens is an abstraction from functional programming. It makes updating complex immutable nested objects easier for us.

For lenses, we have three kinds of available implementations:

  • scalaz.Lens
  • Quicklens- Has more functionality than a Sauron
  • Sauron

Consider for-comprehensions in Scala. What are they syntactic sugars for?

A for-comprehension is one way to carry out the composition of operations on monads. We can replace it with a foreach or a map/flatMap and filter.

What is function currying in Scala?

With Scala currying, we can take a function that takes multiple arguments and turn it into a series of functions that take single arguments each. These come in handy working with higher-order functions. With this, we can also fill in only the arguments we have yet.

scala> def mul(a:Int,b:Int)=a*b

mul: (a: Int, b: Int)Int

scala> mul(3,4)

res48: Int = 12

We can define it as follows:

scala> def mul(a:Int)(b:Int)=a*b

mul: (a: Int)(b: Int)Int

scala> val mid=mul(3)(_)

mid: Int => Int = $$Lambda$1540/90644757@43fe3f7

scala> mid(4)

res49: Int = 12

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.

What is a ‘Scala set’? What are methods through which operation sets are expressed?

Scala set is a collection of pairwise elements of the same type. Scala set does not contain any duplicate elements. There are two kinds of sets, mutable and immutable.

What is a ‘Scala map’?

Scala map is a collection of key or value pairs. Based on its key any value can be retrieved. Values are not unique but keys are unique in the Map.

What is the advantage of Scala?

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

In what ways Scala is better than other programming language?

  • The arrays uses regular generics, while in other language, generics are bolted on as an afterthought and are completely separate but have overlapping behaviours with arrays.
  • Scala has immutable “val” as a first class language feature. The “val” of scala is similar to Java final variables. Contents may mutate but top reference is immutable.
  • Scala lets ‘if blocks’, ‘for-yield loops’, and ‘code’ in braces to return a value. It is more preferable, and eliminates the need for a separate ternary operator.
  • Singleton has singleton objects rather than C++/Java/ C# classic static. It is a cleaner solution
  • Persistent immutable collections are the default and built into the standard library.
  • It has native tuples and a concise code
  • It has no boiler plate code

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;

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.

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.

What is ‘scala trait’ in Scala?

‘Traits’ are used to define object types specified by the signature of the supported methods. Scala allows to be partially implemented but traits may not have constructor parameters. A trait consists of method and field definition, by mixing them into classes it can be reused.

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 behavior will not be reused, then make it a concrete class. Anyhow it is not a reusable behavior.
  • 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.

What are Case Classes?

Case classes provides a recursive decomposition mechanism via pattern matching, it is a regular class which export their constructor parameter. The constructor parameters of case classes can be accessed directly and are treated as public values.

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.

What are implicit parameters in Scala?

Implicit parameter is the way that allows parameters of a method to be “found”. It is similar to default parameters, but it has a different mechanism for finding the “default” value. The implicit parameter is a parameter to method or constructor that is marked as implicit. This means if a parameter value is not mentioned then the compiler will search for an “implicit” value defined within a scope.

What is a closure in Scala?

A closure is a function whose return value depends on the value of the variables declared outside the function.

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.

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.

What is 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.

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”)

How can you format a string?

To format a string, use the .format () method, in scala you can use

Val formatted= “%s %i”.format (mystring.myInt)

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.

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.

Explain ‘Scala higher order’ functions?

Scala allows the definition of higher order functions. These are functions that take other functions as parameters, or whose result is a function. In the following example, apply () function takes another function ‘f’ and a value ‘v’ and applies function to v.

Example:

object Test {

def main(args: Array[String]) {

println( apply( layout, 10) )

}

def apply(f: Int => String, v: Int) = f(v)

def layout[A](x: A) = “[” + x.toString() + “]”

When the above code is compiled and executed, it produces following result.

C:/>scalac Test.scala

C:/>scala Test

[10]

C:/>

 

So, this brings us to the end of the Scala Interview Questions blog.This Tecklearn ‘Top Scala Interview Questions and Answers’ helps you with commonly asked questions if you are looking out for a job in Apache Scala or Big Data Domain. If you wish to learn Apache Scala and build a career in Big Data domain, then check out our interactive, Apache Spark and Scala Training, that comes with 24*7 support to guide you throughout your learning period.

https://www.tecklearn.com/course/apache-spark-and-scala-certification/

Apache Spark and Scala Training

About the Course

Tecklearn Spark training lets you master real-time data processing using Spark streaming, Spark SQL, Spark RDD and Spark Machine Learning libraries (Spark MLlib). This Spark certification training helps you master the essential skills of the Apache Spark open-source framework and Scala programming language, including Spark Streaming, Spark SQL, machine learning programming, GraphX programming, and Shell Scripting Spark. You will also understand the role of Spark in overcoming the limitations of MapReduce. Upon completion of this online training, you will hold a solid understanding and hands-on experience with Apache Spark.

Why Should you take Apache Spark and Scala Training?

  • The average salary for Apache Spark developer ranges from approximately $93,486 per year for Developer to $128,313 per year for Data Engineer. – Indeed.com
  • Wells Fargo, Microsoft, Capital One, Apple, JPMorgan Chase & many other MNC’s worldwide use Apache Spark across industries.
  • Global Spark market revenue will grow to $4.2 billion by 2022 with a CAGR of 67% Marketanalysis.com

What you will Learn in this Course?

Introduction to Scala for Apache Spark

  • What is Scala
  • Why Scala for Spark
  • Scala in other Frameworks
  • Scala REPL
  • Basic Scala Operations
  • Variable Types in Scala
  • Control Structures in Scala
  • Loop, Functions and Procedures
  • Collections in Scala
  • Array Buffer, Map, Tuples, Lists

Functional Programming and OOPs Concepts in Scala

  • Functional Programming
  • Higher Order Functions
  • Anonymous Functions
  • Class in Scala
  • Getters and Setters
  • Custom Getters and Setters
  • Constructors in Scala
  • Singletons
  • Extending a Class using Method Overriding

Introduction to Spark

  • Introduction to Spark
  • How Spark overcomes the drawbacks of MapReduce
  • Concept of In Memory MapReduce
  • Interactive operations on MapReduce
  • Understanding Spark Stack
  • HDFS Revision and Spark Hadoop YARN
  • Overview of Spark and Why it is better than Hadoop
  • Deployment of Spark without Hadoop
  • Cloudera distribution and Spark history server

Basics of Spark

  • Spark Installation guide
  • Spark configuration and memory management
  • Driver Memory Versus Executor Memory
  • Working with Spark Shell
  • Resilient distributed datasets (RDD)
  • Functional programming in Spark and Understanding Architecture of Spark

Playing with Spark RDDs

  • Challenges in Existing Computing Methods
  • Probable Solution and How RDD Solves the Problem
  • What is RDD, It’s Operations, Transformations & Actions Data Loading and Saving Through RDDs
  • Key-Value Pair RDDs
  • Other Pair RDDs and Two Pair RDDs
  • RDD Lineage
  • RDD Persistence
  • Using RDD Concepts Write a Wordcount Program
  • Concept of RDD Partitioning and How It Helps Achieve Parallelization
  • Passing Functions to Spark

Writing and Deploying Spark Applications

  • Creating a Spark application using Scala or Java
  • Deploying a Spark application
  • Scala built application
  • Creating application using SBT
  • Deploying application using Maven
  • Web user interface of Spark application
  • A real-world example of Spark and configuring of Spark

Parallel Processing

  • Concept of Spark parallel processing
  • Overview of Spark partitions
  • File Based partitioning of RDDs
  • Concept of HDFS and data locality
  • Technique of parallel operations
  • Comparing coalesce and Repartition and RDD actions

Machine Learning using Spark MLlib

  • Why Machine Learning
  • What is Machine Learning
  • Applications of Machine Learning
  • Face Detection: USE CASE
  • Machine Learning Techniques
  • Introduction to MLlib
  • Features of MLlib and MLlib Tools
  • Various ML algorithms supported by MLlib

Integrating Apache Flume and Apache Kafka

  • Why Kafka, what is Kafka and Kafka architecture
  • Kafka workflow and Configuring Kafka cluster
  • Basic operations and Kafka monitoring tools
  • Integrating Apache Flume and Apache Kafka

Apache Spark Streaming

  • Why Streaming is Necessary
  • What is Spark Streaming
  • Spark Streaming Features
  • Spark Streaming Workflow
  • Streaming Context and DStreams
  • Transformations on DStreams
  • Describe Windowed Operators and Why it is Useful
  • Important Windowed Operators
  • Slice, Window and ReduceByWindow Operators
  • Stateful Operators

Improving Spark Performance

  • Learning about accumulators
  • The common performance issues and troubleshooting the performance problems

DataFrames and Spark SQL

  • Need for Spark SQL
  • What is Spark SQL
  • Spark SQL Architecture
  • SQL Context in Spark SQL
  • User Defined Functions
  • Data Frames and Datasets
  • Interoperating with RDDs
  • JSON and Parquet File Formats
  • Loading Data through Different Sources

Scheduling and Partitioning in Apache Spark

  • Concept of Scheduling and Partitioning in Spark
  • Hash partition and range partition
  • Scheduling applications
  • Static partitioning and dynamic sharing
  • Concept of Fair scheduling
  • Map partition with index and Zip
  • High Availability
  • Single-node Recovery with Local File System and High Order Functions

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Top Scala Interview Questions and Answers"

Leave a Message

Your email address will not be published. Required fields are marked *