Scala is one of the fastest-growing and trending programming languages. It is known widely for its capability of handling petabytes of big data. It has captured the interest of programmers with its features like high scalability and flexibility. Also, Scala comes with the combined features of object-oriented programming and functional programming, and it can easily run on the (Java Virtual machine).
If you are looking to work as a professional Scala Developer in a reputed organization, you need to appear for the Scala job interviews. Many individuals believe that the interviews for the role of Scala developer are complex.
However, if you develop a good understanding of the fundamental concepts of Scala, you can easily crack an interview. In case you are preparing for a Scala interview, you may want to know the frequently asked Scala interview questions.
Well, in this article, we have summed up the top Scala interview questions that you should know to boost your knowledge as well as improve your chances of making it through your upcoming interview.
Scala Interview Questions and Answers
1. Is Scala a scalable language?
Answer: Like Java, Scala is a general-purpose programming language that runs on JVM and is suitable for creating applications of any size. Scala is also flexible as it allows developers to work on a variety of projects, ranging from small scripts to multi-module applications. Its object-oriented features make it possible for developers to create complex programs easily.
Similarly, as it follows the principles of functional programming, we can reuse Scala code in other project modules. Overall, this programming language can fit any business requirements and is ideal for developing projects of any scale.
2. Explain the first-order function.
Answer: Scala gives you the facility for writing the functions in the form of the literals that can be easily assigned to any variable. Also, you can easily pass such a function to another function as an argument or return it from another function as a value. These types of functions are known as first-order functions.
Below is an example of a first-order function:
x=x*x, which is a first-order function.
val sq=x=x*x
3. Mention some Scala frameworks.
Answer: Below are some popular Scala frameworks:
- Akka Framework: It is used to build concurrent applications usimg a message driven technique, where multiple actors can be used to introduce parallelism and tasks can be assigned to the actors by passing messages to them. To learn more you can visit its official documentation .
- Spark Framework: Apache Spark is a framework which is written in Scala and is designed to perform distributed processing on huge amount of data. It was designed to mitigate the limitations of Hadoop MapReduce by introducing in-memory processing. To learn more you can visit its official documentation .
- Play Framework: Play Framework is used to build web-applications. It is a powerful full-stack MVC framework that allows you to create an application end-to-end including designing the pages of application, creating the rest end points to support features, and integration with databases. It uses Akka and Akka Streams under the cover. For more information, you can visit its official documentation .
- Neo4j Framework: Neo4j is highly scalable and schema free open source graph database. For more details, you can refer to documentation .
- Lift Framework: Lift is an open source framework for designing web applications using Scala language. It does not follow MVC architecture , rather it is modelled upon the View First approach.
- Slick: Slick is a library to support relational database integration just like you are using scala collections. Using Slick you can force typechecking of your database tables, so that errors related to types can be identified at compile time rather than at runtime.
- Bowler Framework
4. Mention the different types of variables in Scala and their differences.
Answer: Scala consists of two types of variables, namely mutable and immutable.
- Mutable variables: You can declare these variables with the help of the “var” keyword, and the value of these variables can be changed during the execution of the program.
- Immutable variables: You can easily declare these variables with the help of the “val” keyword, and the value of these variables cannot be changed during the execution of the program.
var changeMe = "Hey! please update me"
changeMe = "Someone just updated my value"
println(changeMe)
val changeMe = "Hey! please update me"
changeMe = "Try changing me and you will fail" // It will give error "reassignment to val"
Output:
changeMe: String = Hey! please update me
changeMe: String = Someone just updated my value
Someone just updated my value
changeMe: String = Hey! please update me
5. What are the advantages of using Scala?
Answer: Following are some of the key advantages of using Scala:
- Scala is a scalable, testable, and flexible programming language.
- It provides combined features of functional as well as object-oriented programming .
- It is a productive programming language.
- You can use it for implementing concurrent programming.
- You will not get any boilerplate code.
- The arrays in Scala use regular generics.
- It has concise code and native tuples.
6. What are streams in Scala?
Answer: In scala, the streams are the lazy list that will evaluate the elements in the stream only when it needs to. This type of lazy computation will help in improving the performance of the program. It can store infinite sequences without overflowing memory constraints.
val streamInstance = Stream(1,2,3)
val newStream = streamInstance.+:(3)
newStream.take(5).toList
Output:
streamInstance: scala.collection.immutable.Stream[Int] = Stream(1, ?)
newStream: scala.collection.immutable.Stream[Int] = Stream(3, ?)
res0: List[Int] = List(3, 1, 2, 3)
Streams are just like lists and composed of cons(#:: is used for streams while :: is used in List) and empty stream.
val stream = 1 #:: 2 #:: 3 #:: Stream.empty[Int]
println(stream)
Output:
stream: scala.collection.immutable.Stream[Int] = Stream(1, ?)
Stream(1, ?)
7. Mention the different operators in scala.
Answer: Scala supports the below-mentioned operators:
- Arithmetic Operators : Addition(+), Subtraction(-), Multiplication(*), Division(/), Modulus (%)
- Relational Operators: Equal to(==), not Equal to (!=), Greater than(>), Greater than equal to(>=), Less than(<), Less than equl to (<=)
- Logical Operators: Logical AND(&&), Logical OR(||), Logical NOT (!)
- Bitwise Operators: Bitwise AND (&), Bitwise OR(|), Bitwise XOR(^), Bitwise Complement(~), Bitwise Left Shift(<<) , Bitwise Right Shift(>>)
- Assignment Operators: General assignment(=), Add and assign(+=), Subtract and assign(-=), Multiply and Assign(*=) etc
8. Explain recursion in Scala?
Answer: Recursion is a method where a function calls itself and that function is called a recursive function. Using the recursive method, you can break down complicated problems into smaller problems that are easy to solve.
Example:
def factorial(number: BigInt): BigInt = {
if (number ==1 ) 1
else number * factorial(number -1)
}
println(factorial(5))
Output:
120
//println(factorial(10000))
/*
java.lang.StackOverflowError
at scala.runtime.BoxesRunTime.boxToInteger(Recursion.sc:61)
at Day6.A$A93$A$A93.factorial(Recursion.sc:2)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
at Day6.A$A93$A$A93.factorial(Recursion.sc:3)
Output exceeds cutoff limit.
*/
To prevent stack overflow exception, you can further optimise the code and write the code in a tail recursive way. In Tail-recursion last expression of a function is a recursive call to the same function.
Example:
def tailRecursiveFactorial(number: BigInt): BigInt = {
def fact(number: BigInt, result: BigInt): BigInt = {
if(number == 1) result
else fact(number-1, number*result)
}
fact(number, 1)
}
tailRecursiveFactorial(10000)
Output:
tailRecursiveFactorial: (number: BigInt)BigInt
res1: BigInt = 28462596809170545189064132121198688901480514017027992307941799942744113400037644437729907867577847758158840621423175288300423399401535187390524211613827161748198241998275924182892597878981242531205946599625986706560161572036032397926328736717055741975962099479720346153698119897092611277500484198845410475544642442136573303076703628825803548967461117097369578603670191071512730587281041158640561281165385325968425825995584688146430425589836649317059251717204276597407446133400054194052462303436869154059404066227828248371512038322178644627183822923899638992827221879702459387693803094627332292570555459690027875282242544348021127559019169425429028916907219097083690539873747452483372899521802363282741217040268086769210451555840567172555372015852132829034279989818449313610640381489...
9. Explain App in Scala?
Answer: Scala offers a helper class “App” that will store the main method and its members altogether. This will be used for turning the objects into executable programs in a faster way. Also, your customized class can extend the App class to render the executable code. Example:
object Demo extends App {
println("Hello")
}
10. Explain different types of variables' scope.
Answer: Scala supports three different types of variable’s scope that are namely fields, method parameters, and local variables.
- Fields: These types of variables are declared within the objects and you can access them easily from anywhere within the program depending on the access modifiers you use for those variables. You can use “var” and “val” for declaring the fields.
- Method parameters: These variables are strictly immutable and are ideal for passing the values to the methods. In general, you can access them within methods. However, you can also access them outside methods using the reference.
- Local variables: These are the variables that you declare within the method, and you can access these variables within a method.
11. Explain closure in Scala.
Answer: In Scala, closure is a function, and its value depends on the value of one or more variables that are declared outside the closure function.
For example:
val multiplier = (i:Int) => i * 10
In the above example, the only variable that is used is “i”, which is defined as a parameter to the function.
12. Explain traits in Scala.
Answer: In Scala, a trait is a unit that encapsulates a method along with its variables (or fields). Below is an example to understand it better:
trait Display{ //trait
def print()
}
class ClassA extends Display{ //extending trait
def print(){
println("Hello")
}
}
object MainObject{
def main(args:Array[String]){
var a = new ClassA()
a.print()
}
}
13. When to use traits in Scala?
Answer: Well, there are no specified rules for using traits, but we have mentioned some scenarios where you can use a trait:
- If you are not going to reuse the behaviour of any specific class, you have to make that class concrete.
- If you want to focus on efficiency, you can consider using the class.
- You can use the abstract class for inheriting the trait in the Java code.
- You can consider creating a trait if you want to use that class within various unrelated classes.
- Traits can be used if there is need of multiple inheritance since class can not support that.
14. What is the extends keyword in Scala?
Answer: Extends keyword is used as a syntax for implementing inheritance. In Scala, you can extend the main class and create an inherited class using the extend keyword in the same way as that in Java. However, in Java, it comes with two different restrictions that are as follows:
- Method overriding requires you to mention the override keyword while extending the main class.
- You can only pass the primary constructor as a parameter to the base constructor.
Here’s an example of how you can use the extends keyword in Scala:
abstract class ParentClass(name: String) {
def printName()
}
println("Extending abstract class")
class ChildClass(name:String) extends ParentClass(name){
override def printName():Unit= println(name)
}
object ChildClass {
def apply(name:String):ParentClass={
new ChildClass(name)
}
}
ChildClass("TGB").printName()
Output:
defined class ParentClass
Extending abstract class
defined class ChildClass
defined object ChildClass
TGB
15. Explain implicit class with an example.
Answer:
Implicit classes helps to extend functionalities of a class without actually modifying that class. This is useful when you are using a library in your project which is external and you want to add some functionality to it. Such classes are marked with implicit keyword. This keyword makes class primary constructor available for implicit conversion whenever the class is in scope.
You must define an implicit class in one of the following:
- Inside a class
- Inside an object
- Inside a package object
Example:
object ImplicitClassExample {
implicit class StringEntension(strInstance: String) {
def removeVowels: String = strInstance.replaceAll("[aeiou]", "")
def half:String = strInstance.substring(0, strInstance.length/2)
}
}
import ImplicitClassExample._
println("Its a good day".removeVowels)
println("Peek-a-Boo".half)
Output(In REPL):
defined object ImplicitClassExample
import ImplicitClassExample._
Its gd dy
Peek-
16. Explain Partially Applied Function and Currying in Scala?
Answer: During function invocation, if the number of arguments passed are lesser than the number of arguments mentioned in function definition, then the result of expression will be a function again. Such returned functions are known as partially applied functions. As the name suggest, the function is not fully resolved and its partial. This feature helps to give convenience of binding some arguments and leaving the other.
Example:
def sum(a: Int, b: Int, c: Int) = a + b + c
val result1 = sum(1,2,3)
println(result1)
val partiallyAppliedFunction = sum(1, _: Int, _:Int)
println(partiallyAppliedFunction)
println(partiallyAppliedFunction(4,5))
Output:
sum: (a: Int, b: Int, c: Int)Int
result1: Int = 6
6
partiallyAppliedFunction: (Int, Int) => Int = <function>
$line6.$read$$iw$$iw$<function>
10
Currying is a method that can easily transform a function with multiple arguments into a function with a single argument.
For example, the above example is taking 3 arguments; we can write the same example in a curried manner like below:
val res1: (Int, Int) => Int = sum(5)(_: Int)(_: Int) // Here Sum is curried function
val res2: Int => Int = res1(6, _:Int) // While res1 is non-curried
val res3: Int = res2(7)
println(res3)
Output:
res1: (Int, Int) => Int = <function>
res2: Int => Int = <function>
res3: Int = 18
17. What are the different access modifiers available in Scala?
Answer: Scala supports three different types of access modifiers - private, protected, and public.
- Private: You can only access the private members within the class or objects in which they are declared.
For example:
class Outer_class { class Inner_class { private def func() { println("f") } class InnerMost_class { func() // OK } } (new Inner_class).func() // you will get error }
- Protected: You can only access the protected members from the subclass of the class in which the member is declared.
For example:
package pack class Super_class { protected def func() { println("f") } } class Sub_class extends Super_class { func() } class Other { (new Super_class).func() // Error: f is not accessible } }
- Public: For accessing public members, you do not need to specify the “public” keyword. Also, you can access the public members from anywhere.
For example:
class Outer_class { class Inner_class { def func() { println("f") } class InnerMost_class { func() // OK } } (new Inner_class).func() // will print the output }
18. Explain Monad in Scala.
Answer: In scala, a Monad is an object that wraps another object within itself. You can pass the Monad small programs or functions that can easily carry out the data manipulation actions on the underlying object rather than impacting the object directly. In terms of implementation, a monad is a data structure that has provided implementation of map() amd flatmap().
Example of monad : List, etc.
19. What are the default packages in Scala?
Answer: Below are the three default packages in Scala:
- Java.lang._: This package in Java will provide the classes that are basic to the design of this language.
- Java.io.: This Package is used for importing every class in Scala for the available input-output resources.
- PreDef: This package will provide type aliases for the types that are commonly used, such as the immutable collection types like Map, Set, and the List constructors.
20. Explain the terms ‘Null’, ‘Nil’, ‘None’, and ‘Nothing’ in Scala?
Answer: These terms are slightly different in their behaviors.
- Null : null represents that the value is absent. It specifies the absence of type information for complex types. Null(capital N) denotes its type.
- Nil specifies an empty list.
- None specifies that the option has no value in it.
- Nothing is the lowest type in the entire type system. All values under the AnyVal and AnyRef fall under the nothing category. A method that throws an exception uses Nothing as a return type.
Example:
val dataHolder: Null = null
val listExample: List[Nothing] = Nil
val optionalData: Option[String] = Map("Batman" -> "Rises").get("CatWomen") //Output will be None
21. How is the case class different from the regular class in Scala?
Answer: Below we have mentioned some of the characteristics of a Case class that makes it different from the regular class in scala:
- Case class supports pattern-matching.
- For creating an instance of the case class, you do not have to mention the new keyword.
- For case classes, Scala automatically generates the equals(), hashcode(), and toString() methods.
- Scala will automatically generate the accessor methods for the constructor arguments of the case class.
- It provides syntactic convenience since all arguments in parameter list are by default val.
- Case classes provide copy method, which helps to create a new instance easily. This is helpful when you case class has many parameter and only one or two need change.
22. Explain concurrency and parallelism concepts.
Answer: Parallelism is the concept of breaking a single task into multiple small tasks that need to be run at the same time via multiple threads. On the other hand, concurrency is the concept of executing multiple tasks sequentially during overlapping time periods.
If we want to avoid access to a mutable state via multiple threads, we can make use of concurrency. Some actors can behave as both concurrent as well as parallel. For example, Node.js is a single-threaded implementation but is also concurrent due to its event loops.
23. Explain the Scala map.
Answer: Scala maps specify the collection of the key-value pairs, and you can retrieve a value using its respective key. The values of the keys are not unique, but the keys are unique to determine the values referred by them. Like variables, the maps can also be mutable or immutable.
Example:
import scala.collection.SortedMap
import scala.collection.immutable.{HashMap, ListMap}
val immutableMap: Map[String, String] = Map("key" -> "value") // by default immutable map are created
val mutableMap = scala.collection.mutable.Map("key1" -> "value1") // here we need to explicitly mention that map is mutable
mutableMap.update("key1", "value2") // Here value will be updated
val hashMap = HashMap(1 -> "a", 5 ->"b", 3 -> "c" , 32 -> "d")
val listMap = ListMap(1 -> "a", 5 ->"b")
val sortedMap = SortedMap(1 -> "a", 5 ->"b", 3 -> "c" , 32 -> "d")
24. Explain different types of loops in scala.
Answer: Below are the different types of loops that are being used in Scala:
- While Loop: This loop is used for repeating a set of statements until the mentioned while condition becomes true. This loop will test the condition before it executes the loop body.
- Do-While: This loop is somehow similar to the while statement; this loop will go through the body once and then test the specified condition at the end of the loop body. So, the statements within the loop will get executed at least once, whether the condition is true or not.
- For: This loop is used for executing a set of statements multiple times till a specific condition is satisfied.
- Break: This is a loop control statement that terminates the specified loop statement and transfers the control out of the loop. It then executes the immediately following statement.
25. How to declare a function in Scala?
Answer: Below is the syntax for declaring a function in Scala:
def <function_Name> (<list of parameters>) : <return type> = {
//function_body
return <expression> // please note in scala mentioning return keyword is optional
}
In the above syntax, the return type of the function is the valid Scala data type, and the list of the parameters is separated by commas. The return type of the parameter list is optional. Just like Java, we mention the return statement, along with the valid expression if the function returns the value.
26. How to concatenate strings in Scala?
Answer: Below we have mentioned three different ways of concatenating two strings in Scala:
- string1.concat(string2);
- "My name is ".concat("Jim");
- "Hello," + " Friend" + "!"
27. Mention different string methods.
Answer: Below are few example of string methods used in Scala:
- String trim(): This function returns a copy of the string after omitting the leading and trailing whitespace.
- String toUpperCase: This function converts all the characters in the given string to the upper case.
- Char[] to CharArray(): This method allows you to convert the given string to a new character array.
- String[] split(String regex): This method splits the given string around matches of the specified regular expression.
- Int length(): This method returns the length of the mentioned string.
28. How to create an array in Scala?
Answer: Following are the different methods for creating an array in Scala:
- Creation using Array type
val intArray = Array(1,2,3)
- By using the ofDim for declaring a multidimensional array.
var my_Matrix = scala.Array.ofDim[Int](2,3)
By using the Range() method for generating an array that holds a specific sequence of increasing integers mentioned within a given range. Example:
Array.range(12,24,2) // Output: Array(12, 14, 16, 18, 20, 22)
Note: Definition of Range method: def range( start: Int, end: Int, step: Int ): Array[Int]
29. What is exception handling in Scala?
Answer: Exception are the runtime errors that one can get during program execution. We can also call them the exceptional cases which might lead to program failure. These exceptions either needs to be handled for graceful termination of the program or they will mark the program as failed. The exception handling concept in Scala works the same as in Java. In Scala, exceptions can either be handled using
- try catch block
To perform exception handling we should put the statements inside try block which might lead to exception. Whenever an exception is thrown, it is handled using a catch block. Scala allows you to handle any exception in a single block and then carry out the set of instructions stored within the catch block.
Here’s an example of the try-catch block:
try {
val input_data = new FileReader("data.txt")
println("This statement will not execute if exception occur in the above statement and program flow will directly go to catch block")
} catch {
case ex: FileNotFoundException => {
println("File not found")
}
case ex: IOException => {
println("Exception in I/O")
}
} finally {
println("Hey Coders! I am finally block and i will execute no matter if the exception occurs or not. People use me to free up resources if they are being created in the try block. Example: File Readers, Database connections etc")
println("Exit the code...")
}
}
- One can also use the Try Match block for handling exceptions. Try is either a success of type T or failure containing an exception(instance of java.lang.Throwable). Try helps to work with asynchronous computations that might be complete with an exception or with some result.
import scala.util.{Try, Success, Failure}
Try {
val x = 5/0
println("Exception thrown so i will not execute")
x
} match {
case Success(data) => println(data)
case Failure(exception) => println(exception.getMessage) // Output will be: / by zero
}
A programmer can also throw exceptions using the throw keyword. This functionality is used to throw custom-type exceptions. Below is an example of how we can create a custom exception class and how we can throw Exceptions.
import scala.util.{Try, Success, Failure}
case class CustomException(errorMessage: String) extends Exception(errorMessage: String)
Try {
val x = 5/0
println("Exception thrown so i will not execute")
x
} match {
case Success(data) => println(data)
case Failure(exception) => throw CustomException("Divide by zero error")
}
Output:
import scala.util.{Try, Success, Failure}
defined class CustomException
CustomException: Divide by zero error
... 34 elided
30. Explain Scala sets and the operations that one can perform on sets.
Answer: A Set is a collection that stores unique elements. Sets can be either mutable or immutable. By default, Scala uses immutable sets. Below are some methods for performing set operations:
- head: It will return the head (that is the first element) of the set,
- tail: It will return the entire set except for the head element.
- isEmpty: It will check if the given set is empty and returns the Boolean value.
31. Why is Scala preferred over other programming languages?
Answer: Below are some reasons why Scala has been preferred over other programming languages:
- It has the features of both object-oriented and functional programming.
- Scala is a simple language that is easy to code and compile.
- It can implement the concept of concurrency that makes the synchronization process easier.
- You can even add third-party libraries in the language constructs format.
- It allows you to work in a multicore architecture environment.
32. Explain BitSet in Scala.
Answer: BitSet is considered to be the collection of small integers that are represented as the bits of the larger integers. You can easily add multiple items to BitSet with the help of the “++” operator. BitSets can be mutable and immutable, and they can also be sets of non-negative integers.
33. Explain what are the restrictions while using the extend keywords in Scala.
Answer: In scala, extend keyword comes with two restrictions - the first one is overriding where we have to use the override keyword, and the second is the primary constructor that passes the parameters to the base constructor.
34. Explain the anonymous function in Scala.
Answer: This function is also known as the function literals in the source code. During the run time, the instance of these function literals will get created as objects that are known as function values, which is an easier way for defining the anonymous functions. These are the functions that dont have any name. They can be used to create inline functions.
For example:
val multiplier = (x: Int, y: Int) => x * y
multiplier(2,3)
Output:
multiplier: (Int, Int) => Int = <function>
res5: Int = 6
35. Explain the difference between Scala and Java.
Answer:
Scala | Java |
Scala comes with the support for closures. | Java does not come with the support for the closures. |
It comes with the Type-inference. | It does not support the Type-inference. |
Scala provides the facility of nested functions. | Java does not provide the facility of the nested functions. |
It supports concurrency. | It does not support concurrency. |
Scala comes with the support for the different traits. | It does not support traits. |
It has support for the Domain-Specific Language or DSL. | Java does not support the Domain Specific Language. |
36. Explain list operations in Scala.
Answer: List is one of the commonly used collection is Scala which can store homogeneous types. The list that can store element of type T is written as List[T]. Lists are immutable, which means elements of the list can't be changed by assignment. Below are the commonly used methods on List:
- head : It retrieves the first element of the list
- tail: It returns a list leaving the first element of the list
- last: It returns the last element of the list
- isEmpty: returns true if the list is empty
- map: It is used to iterate over the list. You can also provide any operation definition that you want to perform on the list
- flatmap: It works just like a map with the only difference is, it also breaks the internal grouping of elements to generate list. This operation can be understood as a combination of map and flatten method
Example:
val listOfString = List("Cat", "Dog", "Rat")
listOfString.head
listOfString.tail
listOfString.last
listOfString.isEmpty
listOfString.map("Element:" + _ )
listOfString.flatMap("Element :" + _)
Output:
listOfString: List[String] = List(Cat, Dog, Rat)
res0: String = Cat
res1: List[String] = List(Dog, Rat)
res2: String = Rat
res3: Boolean = false
res4: List[String] = List(Element:Cat, Element:Dog, Element:Rat)
res5: List[Char] = List(E, l, e, m, e, n, t, , :, C, a, t, E, l, e, m, e, n, t, , :, D, o, g, E, l, e, m, e, n, t, , :, R, a, t)
-
Concatenation on list
val list1 = List(1, 2)
val list2 = List(3,4)
list1 ::: list2
Output:
list1: List[Int] = List(1, 2)
list2: List[Int] = List(3, 4)
res0: List[Int] = List(1, 2, 3, 4)
- Preappend on list
8 :: list1
Output:
res1: List[Int] = List(8, 1, 2)
- Append on list
list1 :+ 10
Output:
res2: List[Int] = List(1, 2, 10)
37. Mention the difference between var and value.
Answer: In Scala, you can easily define a variable with the help of either “val” or “var” keywords. Also, there is a difference in val and var methods of declaring a variable. Var is just like the declaration in Java, but the val is somehow different. If a variable is declared using the “val”, then the value cannot be changed as it is immutable. You can set the value of the “val” variable only once. But the variables that are declared with the help of the var keyword are mutable and their values can be changed accordingly.
38. How to format a string in Scala?
Answer: For formatting a string, you can use the .format() method as illustrated below: val formatted_val= “%s %i”.format (mystring.myInt).
You can also use String interpolators to format a string in scala. (They were introduced in Scala 2.10.0 onwards). Below are the different type of interpolators with their examples:
1) The "s" interpolator
val username = "TGB Learner"
s"Hey ${username}. Its time to start writing some code examples"
In "s" interpolator the string has to start with s followed by Double quotes, where you can add any content which could be concatenated to string. To insert some variables and expressions, you can use the curly braces as mentioned in the above example.
2) The "f" interpolator
"f" should be preappended to a string to format the string. This type of interpolator works similarly to printf statements in another language where you need to specify variable reference after the variable.
val name: String = "Geet"
val weight: Double = 54.4
val fInterpolatorExample = f"Hi $name%s ! Your weight is $weight%2.2f kg"
39. Explain method parameters.
Answer: Method parameters are the values that are passed to the method. These parameters are immutable; their values cannot be changed and are accessible only from inside a method. You can use the reference in order to access them from outside the method.
40. Why are options used in Scala?
Answer: It is used for wrapping the missing value in Scala.
41. How to compile the Scala code?
Answer: First, create the Scala code in any appropriate IDE. The code will get converted to the byte code, and then it will get transferred to the JVM (Java Virtual Machine) for compilation .
42. Explain features of Yield in Scala.
Answer: Below are the features of Yield in Scala:
- You can use it as a loop.
- It will generate value for each iteration.
- It can use map, Flapmap, and other filters along with the nomads.
43. Explain the infinite loop in Scala.
Answer: An infinite loop is a scenario when the condition is always true and the loop keeps on running endlessly.
44. Mention identifiers in Scala.
Answer: There are four types of identifiers in Scala that are as follows:
- Alphanumeric identifiers
- Operator identifiers
- Mixed identifiers
- Literal identifiers
45. Mention the implicit parameter precedence.
Answer: The following is the precedence of the implicit parameters:
- First, Locally declared implicit parameters
- Second, Imported implicit
- Third, Outer scope (ex- a class for a method
- Fourth, Inheritance
- Fifth, Package object
- Last, An implicit scope like companion objects
46. Explain lens in Scala.
Answer: It is an abstraction from functional programming, which allows you to update complex immutable nested objects easily. You can implement lens by using three different methods listed below:
- scalaz.Lens
- Quicklens- Has more functionality than a Sauron
- Sauron
47. Define predominant operators in Scala.
Answer: Arithmetic operators, Relational operators, Logical operators, Bitwise Operators, and Assignment Operators.
48. Explain ofDim() function.
Answer: It is a function that will help you in creating a multidimensional array. Also, it allows you to store data in multiple dimensions just like a matrix.
49. Explain the auxiliary constructor for a class.
Answer: You can use the “this” keyword for defining an auxiliary constructor of a class. If you are defining more than one method in the class body, then they will be treated as auxiliary constructors. The first statement of the auxiliary constructor should either be the call to the primary constructor or another auxiliary constructor.
50. Is tuple immutable?
Answer: Yes, tuples are immutable when we use them in an array or list as they can hold objects with different data types.
Example:
val tupleStruct: (String, Int, String, String) = ("Dog", 4, "Brown", "Pomeranian")
println(tupleStruct._1)
println(tupleStruct._2)
println(tupleStruct._3)
println(tupleStruct._4)
Output:
tupleStruct: (String, Int, String, String) = (Dog,4,Brown,Pomeranian)
Dog
4
Brown
Pomeranian
while tuples are immutable but there is always an option to create a new object with updated values just like we create a new instance for case classes using copy method.
tupleStruct.copy(_3 = "White")
Output:
res: (String, Int, String, String) = (Dog,4,White,Pomeranian)
Conclusion
Once you go through the aforementioned Scala interview questions, you will be able to polish up your knowledge and prepare for your upcoming interview. Scala is a popular programming language that is growing fast. Also, Scala developers are in high demand in the market; thus, you can consider adding it to your skillset.
People are also reading:
Leave a Comment on this Post