1. 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.
2. . 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.
3. 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.
4. 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..
5. 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.
6. 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. (Scala Interview Questions)
7. 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.
8. What Are The Differences Between Array And Arraybuffer In Scala?
Differences between Array and ArrayBuffer in Scala:
Array is fixed size array. We cannot change its size once its created.
ArrayBuffer is variable size array. It can increase or decrease it’s size dynamically.
Array is something similar to Java’s primitive arrays.
ArrayBuffer is something similar to Java’s ArrayList.
9. Does A Companion Object Access Private Members Of It’s Companion Class In Scala?
Generally, private members means accessible only within that class. However Scala’s Companion class and Companion Object has provided another feature.
In Scala, a Companion object can access private members of it’s Companion class and Companion class can access it’s Companion object’s private members.
10. How Many Values Of Type Nothing Have In Scala?
In Scala, Nothing type have no values that is zero. It does not have any values. It is a subtype of all Value classes and Reference classes.
11. What Is The Main Design Decision About Two Separate Keywords: Class And Object In Scala? How Do We Define Instance Members And Static Members In Scala?
In Scala, we use class keyword to define instance members and object keyword to define static members. Scala does not have static keyword, but still we can define them by using object keyword.
The main design decision about this is that the clear separation between instance and static members. Loosely coupling between them. And other major reason is to avoid static keyword so that Scala will become a Pure-OOP Language.
12. What Is Range In Scala? How To Create A Range In Scala?
Range is a Lazy Collection in Scala. Range is a class available in ‘scala’ package like ‘scala.Range’. It is used to represent a sequence of integer values. It is an ordered sequence of integers.
13. How To Implement Interfaces In Scala?
As we know from Java background, we use interface to define contact.
However, there is no interface concept in Scala. Even, Scala doesn’t have interface keyword. Scala has a more powerful and flexible concept i.e. trait for this purpose. (Scala Interview Questions)
14. How Does It Work Under-the-hood, When We Create An Instance Of A Class Without Using ‘new’ Keyword In Scala? When Do We Go For This Approach? How To Declare Private Constructors In Scala?
In Scala, when we create an instance of a Class without using ‘new’ keyword, internally it make a call to appropriate apply method available in Companion object. Here appropriate apply method means that matched with parameters.
When do we choose this option: When we need to provide private private constructor and we need to avoid using ‘new’ keyword, we can implement only apply method with same set of parameters and allow our class users to create it without new keyword.
15. Why Scala Does Not Have “static” Keyword? What Is The Main Reason For This Decision?
As we know, Scala does NOT have “static” keyword at all. This is the design decision done by Scala Team.
The main reason to take this decision is to make Scala as a Pure Object-Oriented Language. “static” keyword means that we can access that class members without creating an object or without using an object. This is completely against with OOP principles.
If a Language supports “static” keyword, then that Language is not a Pure Object-Oriented Language. For instance, as Java supports “static” keyword, it is NOT a Pure Object-Oriented Language. But Scala is a Pure Object-Oriented Language.
16. Difference Between Array And List In Scala?
Arrays are always Mutable where as List is always Immutable.
Once created, We can change Array values where as we cannot change List Object.
Arrays are fixed-size data structures where as List is variable-sized data structures. List’s size is automatically increased or decreased based on it’s operations we perform on it.
Arrays are Invariants where as Lists are Covariants.
17. 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
18. 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.
19. 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.
20. 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. (Scala Interview Questions)
21. 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.
22. 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.
23. 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 provide 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.
24. 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.
25. 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. (Online Training Institute)
26. 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.
27. 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
- For a detailed piece on its benefits, read up on Advantages of Scala.
28. 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 Interview Questions)
29. 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.
30. 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.
31. 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.
32. 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.
33. 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. (Apache Tomcat Training Videos)
34. 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.
35. What Are Option, Some And None In Scala?
‘Option’ is a Scala generic type that can either be ‘some’ generic value or none. ‘Queue’ often uses it to represent primitives that may be null.
36. What Is Diamond Problem? How Scala Solves Diamond Problem?
A Diamond Problem is a Multiple Inheritance problem. Some people calls this problem as Deadly Diamond Problem.
In Scala, it occurs when a Class extends more than one Traits which have same method definition.
Unlike Java 8, Scala solves this diamond problem automatically by following some rules defined in Language. Those rules are called “Class Linearization”. (Scala Interview Questions)
37. What Is The Best Framework To Generate Rest Api Documentation For Scala-based Applications?
Swagger is is the best tool for this purpose. It is very simple and open-source tool for generating REST APIs documentation with JSON for Scala-based applications.
If we use Play with Scala to develop your REST API, then use play-swagger module for REST API documentation.
If we use Spray with Scala to develop your REST API, then use spray-swagger module for REST API documentation.
38. What Are The Advantages Of Play/scala Stack To Develop Web Applications?
The following are the major advantages of Play/Scala stack to develop web applications:
Open Source: Play is an Open-source free-software framework to develop web applications.
Better Productivity: Play framework’s Auto-reload feature improves Developer Productivity. No need to build, deploy and test our changes. Just do our changes and refresh the page to see our changes.
Stateless and Easy to Develop REST API: Play is HTTP based stateless model to serve web requests so it is very easy to develop REST API or RESTful Web Services.
Better Error-Handling: If we develop our web application using Play framework,it informs all errors in the browser in very useful format. It shows error message, the file location, line number where error occurred, highlighting the code-snippet to understand the error very easily.
High Performance and Better Scalability With Reactive: Play framework is developed by following Reactive design patterns and it is built on top of Netty sever to utilize Non-blocking IO Feature. Because of this feature, we can develop very highly Scalable and performance applications very easily.
Easy to Extend: Play is very flexible framework and supports developing plug-ins very easy to extend it’s features and functionality.
Highly Concurrency and Better Parallelism: As both Scala and Play supports Functional Programming, it is very easy to develop Highly Concurrency and Better Parallelism applications very easily because FP supports Immutability, Pure Functions (Functions without side-effects), Pattern Matching, Actor Model etc.
Better Reusability, Easy to Test and More Modular: As both Scala and Play supports Functional Programming, we can develop more modular and reusable applications. It is also very easy to test more modular applications.
39. What Is Extractor In Scala? What Is The Difference Between Constructor And Extractor In Scala? What Is The Use Of Extractor In Scala?
Not only in Java and Scala, in almost all OOP languages Constructor is used to create (or assemble) an object or an instance of a Class using it’s parameters (or components). Extractor is quite opposite to Constructor.
In Scala, Extractor is used to decompose or disassemble an object into it’s parameters (or components).
In Scala, apply method is a Constructor. Internally, Extractor uses unapply method to decompose an objects into it’s parts (or parameters). In Scala, Extractor is mainly used in Pattern Matching concept. We will discuss Pattern Matching concept soon.
40. What are Advantages of Using Scala?
Scala was created to enable programmers to use OOP and FP together: It brings OOP concepts such as first-class modules, dot syntax, and first-class type classes/instances together with FP concepts such as higher order functions and pattern matching.
Other advantages include type safety, a concise syntax, flexibility, and scalability. Built on top of the JVM, it is both compatible and interoperable with Java. Scala can perform many of the same tasks as Java with fewer lines of code without sacrificing readability.
Finally, support for FP makes Scala great for parallel programming, where having immutable data and state really comes in handy. It is easy to divide up the work for a given task across multiple processors in distributed computing. This is one of the reasons Spark was built with Scala.
41. What are the advantages of using Apache Spark over Hadoop MapReduce for big data processing?
Simplicity, Flexibility and Performance are the major advantages of using Spark over Hadoop.Spark is 100 times faster than Hadoop for big data processing as it stores the data in-memory, by placing it in Resilient Distributed Databases (RDD).
Spark is 100 times faster than Hadoop for big data processing as it stores the data in-memory, by placing it in Resilient Distributed Databases (RDD).
Spark is easier to program as it comes with an interactive mode.
It provides complete recovery using lineage graph whenever something goes wrong. (Scala Interview Questions)
42. What is lineage graph?
The RDDs in Spark, depend on one or more other RDDs. The representation of dependencies in between RDDs is known as the lineage graph. Lineage graph information is used to compute each RDD on demand, so that whenever a part of persistent RDD is lost, the data that is lost can be recovered using the lineage graph information.
43. What is the significance of Sliding Window operation?
Sliding Window controls transmission of data packets between various computer networks. Spark Streaming library provides windowed computations where the transformations on RDDs are applied over a sliding window of data. Whenever the window slides, the RDDs that fall within the particular window are combined and operated upon to produce new RDDs of the windowed DStream.
44. What are the features of Scala?
Features of Scala are:
- Type inference
- Singleton object
- Lazy computation
- Concurrency control
- Rich collection set
- String interpolation
- Higher order function
- Case classes and Pattern matching
45. 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.
46. 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.
47. 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.
48. 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.
49. 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.
50. What Is Case Class? What Is Case Object? What Are The Advantages Of Case Class?
Case class is a class which is defined with “case class” keywords. Case object is an object which is defined with “case object” keywords. Because of this “case” keyword, we will get some benefits to avoid boilerplate code.
We can create case class objects without using “new” keyword. By default, Scala compiler prefixes “val” for all constructor parameters. That’s why without using val or var, Case class’s constructor parameters will become class members, it is not possible for normal classes.
Advantages of case class:
- By default, Scala Compiler adds toString, hashCode and equals methods. We can avoid writing this boilerplate code.
- By default, Scala Compiler adds companion object with apply and unapply methods that’s why we don’t need new keyword to create instances of a case class.
- By default, Scala Compiler adds copy method too.
- We can use case classes in Pattern Matching.
- By default, Case class and Case Objects are Serializable.
(Scala Interview Questions)
51. How Scala Solves Inheritance Diamond Problem Automatically And Easily Than Java 8?
If we use Java 8’s Interface with Default methods, we will get Inheritance Diamond Problem. Developer has to solve it manually in Java 8. It does not provide default or automatic resolution for this problem.
In Scala, we will get same problem with Traits but Scala is very clever and solves Inheritance Diamond Problem automatically using Class Linearization concept.
52. What Is Option In Scala? What Are Some And None? What Is Option/some/none Design Pattern In Scala?
In Scala, Option is used to represent optional values that is either exist or not exist.
Option is an abstract class. Option has two subclasses: Some and None. All three (Option, Some and None) are defined in “scala” package like “scala.Option”.
Option is a bounded collection in Scala, which contains either zero or one element. If Option contains zero elements that is None. If Option contains one element, that is Some.
Some is used to represent existing value. None is used to represent non-existent value.
def get(val index: Int): Option[String]
Let us assume that this method is from List. This method has a return type of Option[String]. If List contains elements, this get method returns “Some[String]” element available in that index position. Otherwise, it returns “None” (that is no elements)
Some is a case class and None is an Object. As both are case class/object, we can use them in Pattern Matching very well.
The combination of all these three definitions is known as Option/Some/None Design Pattern in Scala.
- More Modular
- Easier to understand Or Easier reason about
- Easier to test
- Less prone to bugs
- Easier to reuse
- Easier to Parallelism and generalize
54. How Scala Supports Both Highly Scalable And Highly Performance Applications?
As Scala supports Multi-Paradigm Programming(Both OOP and FP) and uses Actor Concurrency Model, we can develop very highly Scalable and high-performance applications very easily.
55. Explain The Diffrence Between Concurrecy And Parallelism?
It’s important to understand the difference between concurrency and parallelism when composing multithreaded programs. Concurrency is the ability to handle lots of things at once, such as a web server handling multiple requests. When one task starts, the program does not have to wait for it to finish before starting another task. In Scala, concurrency is handled with constructs called actors.
Parallelism is a distinct concept that is more concerned with the actual simultaneous execution of said tasks, often in the context of breaking up a task into smaller subtasks that can be processed simultaneously across multiple threads and/or cores. Parallel collections, futures, and the Async library are all examples of parallelism in Scala. (Scala Interview Questions)
56. Why is there a need for broadcast variables when working with Apache Spark?
These are read only variables, present in-memory cache on every machine. When working with Spark, usage of broadcast variables eliminates the necessity to ship copies of a variable for every task, so data can be processed faster. Broadcast variables help in storing a lookup table inside the memory which enhances the retrieval efficiency when compared to an RDD lookup ().
57. What square measure implicit parameters in Scala?
Implicit parameter is that the manner that permits parameters of a technique to be “found”. It’s like default parameters, however it’s a special mechanism for locating the “default” worth. The implicit parameter could be a parameter to methodology or builder that’s marked as implicit. This implies if a parameter worth isn’t mentioned then the compiler can explore for associate degree “implicit” worth outlined among a scope.
58. What’s the distinction between power unit and value?
In scala, you’ll outline a variable victimization either a, val or power unit keywords. The distinction between val and power unit is, power unit is far like java declaration, however val is small completely different. we have a tendency to cannot modification the relevance purpose to a different reference, once the variable is asserted victimization val. The power unitiable outlined victimization var keywords square measure changeable and may be modified any range of times.
59. What’s formula tail in scala?
‘Recursion’ could be a perform that calls itself. A perform that calls itself, as an example, a perform ‘A’ calls perform ‘B’, that calls the perform ‘C’. it’s a way used oftentimes in practical programming. so as for a tail algorithmic, the decision back to the perform should be the last perform to be performed.
60. When Can You Use Traits?
- There is no specific rule when you can use traits, but there is a guideline which you can consider.
- If the behaviour will not be reused, then make it a concrete class. Anyhow it is not a reusable behaviour.
- In order to inherit from it in Java code, an abstract class can be used.
- If efficiency is a priority then lean towards using a class
- Make it a trait if it might be reused in multiple and unrelated classes. In different parts of the class hierarchy only traits can be mixed into different parts.
- You can use abstract class, if you want to distribute it in compiled form and expects outside groups to write classes inheriting from it.
61. 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.