Tutorials Hut




  • Scala Interview Questions And Answers

    In this article we will see top Scala Interview Questions.

    1)   What is Scala?

    Scala is a functional programming language, it is JVM based and uses JDK 8 for development JVM to run. It supports java libraries as well.

    scala

    2) What is a ‘Scala set’?

    Scala set is a data type in Scala collection which can hold unique similar types of values. It does not allow duplicate values. Scala set comes in two flavors one mutable and another immutable. We can reassign a mutable set while immutable does not allow reassignment or change in value.

    3) What is a ‘Scala map’?

    Scala map is a data type in Scala collection which can hold key and value pairs as an element. Scala map is similar to Java Map. On the map we can’t have duplicate keys.

    4) Please tell us features and advantages of Scala ?

    • Functional programming language.
    • Concise because a lot of logic can be written in a few lines.
    • Less error.
    • Supports all java libraries.
    • JVM based.
    • Provides simple implementation of concurrency.
    • Easy to scale, maintain and test.
    • Capable of handling big data processing.

    5) In what ways Scala is better than other programming language?

    • It is a functional programming language and supports functional programming principles.
    • It is JVM based and supports java libraries as well.
    • It also supports object oriented programming.
    • Syntaxes are concise and we can write multiple lines of code in a few lines.
    • It has no boilerplate code.
    • Immutable and mutable variables can be easily created with var and val.
    • Provides simple libraries to implement concurrency.
    • It is capable of processing big data.
    • It supports type inference and so variable type declaration is optional.

    6)   What are the Scala variables?

    Scala variables are used to hold different data types and then we apply logic on them. The two types of variables are var and val. Var values may mutate or update and in case of val values can’t mutate or change.

    Example:

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

    7)   Mention the difference between an object and a class ?

    A class is a skeleton or blueprint of real world objects where definitions are provided and the object is an instance of class. For example Tree can be a class where we can define different properties of tree and tree1 can be an object or instance of Tree class created using class blueprint.

    8) What is recursion tail in Scala?

    Recursion is a way to call own or same function from the function multiple times until final results are calculated, for example function a() calling itself again and again. In tail recursion call to function must be the last function to be performed.

    9) What is the ‘scala trait’ ?

    Trait in scala is a way to declare un implemented methods which the concrete or actual class is forced to implement while using trait. Trait is similar to class with multiple methods but without any body and class which implements trait is bound to implement those methods. Trait is similar to Java Interface.

    10) When can you use traits?

    If you want to define some standard methods across application and business logic, you may create traits with method signature and force developers to implement these methods and follow the standard. It helps in making applications loosely coupled and abstract.

    11) What are Case Classes?

    Case class is a pojo class or a class which has variables with inbuilt getter and setter methods, if you have to create some model where some variables and getter and setter will be there then case class is the option in Scala.

    12) What is the use of tuples in Scala?

    Tuples are pair data types, if you want to hold different data types in one variable and pass them, return them or use them then can declare them as a tuple.

    A tuple variable may hold Int, Float and many different data types together.

    Example:

    val student: (Int, String) = (1001, “Rahul”)

    Use of tuple : student._1 (will access 1001)

            Student._2 (will access “Rahul”)

    13) What is function currying in Scala?

    Currying is a functional programming concept where we can define a function which may take more than one parameter independent and not altogether.

    Example:

    object Currying {
    def sumUsingCurry(a: Int)(b: Int) = a+b
    def main(args: Array[String]): Unit = {
    val firstPartCalled = sumUsingCurry(10)_
    val sum = firstPartCalled(20)
    println(sum)
    }
    }

    14) What are implicit parameters in Scala?

    Implicit parameters are similar to default parameters in function or constructor but no need to provide them, code looks within scope all to find any implicit to resolve it.

    15) What is a closure in Scala?

    Closure is a function which can even be held in a variable.

    Example:

    val myClosureTripleIt= (a: Int) => a*c

    16) What is Monad in Scala?

    Monad is a FP principle which can be implemented in Scala, it contains a map for transformation from one type to another and also a way to take them out of a container. See below for the Monad example.

    case class MyContainer[A](things: A) {
      def map[B](fn: (A) => B): MyContainer[B] = MyContainer(fn(things))
      def flatten = things
      def flatMap[B](fn: (A) => MyContainer[B]): MyContainer[B] = fn(things)
    }

    17) What is Scala anonymous function?

    While writing the function’s definition we can simply provide or create definition without any regular declaration (using def) and such functions are called anonymous. Scala has a lot of anonymous functions.

    18) Explain ‘Scala higher order’ functions?

    A higher order function is such a function which can take a function as input or return another function as return type. Scala is a functional programming language and so everything in Scala is a function. Good example of HOD in Scala API is a map where we can pass functions and do operations without mutating the state of variables.

    Example of HOD function with map

    object HOD {
    val myDoubleFunction: Int => Int = (x: Int) => x*2
    def main(args: Array[String]): Unit = {
    val intList = List(1, 2, 3)
    val doubledIntList = intList.map(myDoubleFunction)
    println(doubledIntList)
     }
    }

    19) What is the difference between var and val (value) in Scala?

    In Scala val and var both are used to declare variables, var ensures that value of variable can be changed or mutated after assignment but val ensures value can’t be reassigned or mutated. var is used for normal variables and val is used to make variables like final in Java.

    20) What are option, some and none in Scala?

    In Scala if we are not sure about a variable that it will hold value or will be null/empty/nothing in that case we use option which means optional and hence may have some value or may be none (means nothing).

    Examples:

    val name: Option[String] = Some(“Ron”)
    val address: Option[String] = None

    21) How to append in Scala list?

    We can append elements with :+ and append another list with ++=.

    Example:

    Var myList = List.empty
    myList  :+= “John”
    myList ++= List(“tom”, “Ron”)

    22) How to use a map to transform in Scala?

    We can apply map() on List or Seq or Map. It is very simple to use it and transform the values.

    Example:

    val myList = List(“Tom”, “Rom”, “Jon”)
    myList.map(name => “Hello ”+name)

    23) What is mutable and immutable and which Scala prefers?

    Mutable means may change or reassign new values, immutable means can’t change and we can’t reassign once some value is assigned. Immutable is similar to final in Java. Scala prefers immutable to avoid any abnormal behavior or change in values.

    24) What are monoids in Scala ?

    Monoids are data types in Scala which helps in doing binary operations and also defines empty / identity methods.

    Example:

    object MonoidsExample {
      //Monoid data structure or type class
      trait Monoid[T] {
    	//should have identity rule and identity element
    	def empty : T // name can be identity, empty, zero element
    	def combine(arg1: T, arg2: T): T // can be add, op, combine etc.
      }
    
      //Example Int addition monoid
      val indAdditionMonoid = new Monoid[Int] {
    	override def empty: Int = 0
    	override def combine(arg1: Int, arg2: Int): Int = arg1+arg2
      }
    }

    25) What are the different types of Scala literals?

    The different types of literals in Scala are –

    • Integer
    • Floating points
    • String
    • Chars
    • Symbols
    • Boolean etc.

     26) What is a companion object in Scala?

    If we declare an object class with the same name as class in Scala then this object is called companion object.

     Example:

    Check below example where MyClass is a companion class and with the same name a companion object is created as well.

    class MyClass { //Companion class
    def printFilename() = {
         println(SomeClass.HiddenFilename) // private member is accessed
    }
    }
    object MyClass { //Companion object
    private val HiddenFilename = "/tmp/foo.bar"
    }

    27) What is partial function in Scala?

    A partial function is a function which returns output for some input values but does not return output for every input or simply not defined for some other values. Usually a function gives output for every input but in partial functions it sometimes is not defined for certain inputs and we can check it as well.

     Example:

    object PartialFunctions {
    val doubleThePositiveNumber = new PartialFunction[Int, Int] {
    def apply(data: Int) = data*2
    def isDefinedAt(data: Int) = data >0
      }
    def main(args: Array[String]): Unit = {
    println(doubleThePositiveNumber(10))
     }
    }

    Output

    20

     28) What is pure and impure function in Scala?

    Pure Function: A pure function is a function which does it work without doing any other activity outside its scope for example updating other variables outside or interacting with consoles or databases. The function does what it is defined for and does not hide any side activity.

     Example:

     def add(a: Int, b: Int) = a+b

     Impure Function: A impure function is a function which does side activities and changes variables outside

    Of its scope or interacts with consoles or data bases.

     Example:

    println(“hello”)

     29) What are Sealed class/traits in Scala?

    A class or train in scala can be marked sealed using the “sealed” keyword. It ensures that all sub classes or subtypes are declared within the same file, this is useful if we want to keep all related classes to that trait in the same file.

     Example

    All subclasses of Student class should be in the same file else it will give error.

    sealed abstract class Student
    case class ArtStudent() extends Student
    case class ScienceStudent() extends Student

     30) Tell us a few Scala base frameworks and their use?

    •   Play – Web development.
    •   Akka Http – Web development.
    •   Spark – Big data, machine learning etc.
    •   Lift – Web development
    •   Slick – DB connection and operations.

    Reference


















  • Leave a Reply

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