Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Sunday, September 10, 2023

Top 30 Scala and Functional Programming Interview Questions and Answers

Hello guys, if you are preparing for Scala Developer interview and looking for frequently asked Scala questions for practice then you have come to the right place. Earlier, I have shared best Scala courses, Scala books, and best Scala Frameworks and in this article, I am going to share 30 Scala Questions from past interviews. Scala is a programming language which aims to provide best of both object-oriented programming and functional programming world. It not only allows you to  construct elegant class hierarchies for maximum code reuse and extensibility but also allows you to implement their behavior using higher-order functions and other functional programming technique. It is touted as one of the languages which can probably take over Java, though it didn't happen especially after Java 8 release which also provides some functional programming tools to Java e.g. lambda expression and stream

Nevertheless, Scala is a good language and created by following best practices from several other programming languages including Java. Scala is an acronym for “Scalable Language”. This means it is designed by keeping scalability in mind. Many companies e.g. Twitter, LinkedIn, and Intel uses it for their mission-critical application.

One of the key strength of Scala is its concise syntax and less ceremony i.e. it is way less verbose than Java. You can write less and do more because the Scala compiler is doing a lot of work for you and that's why many developers also use Scala as a scripting language. Though, for some, it means Scala is less readable than Java. You can't make everyone happy.

Another great thing about Scala is that it offers a nice mix of object-oriented and functional programming concepts. The language support class and every value is an object and every operation is a method call.  Many common object oriented design patterns in other languages have built-in support for Scala. For example, Singleton pattern is supported through object definitions and Visitor pattern is supported through pattern matching.

On the other hand, Scala is also a full-blown functional language. It has everything you would expect from a functional programming language like Haskel or Lisp e.g. first-class functions, a library with efficient immutable data structures, and a general preference of immutability over mutation.

One more great thing about Scala is that it make full use of mature Java resources, it allows you to use Java libraries in Scala project. Scala code is compiled into a bytecode which can be understood by JVM and by using implicit classes, Scala even allows you to add new operations to existing classes, no matter whether they come from Scala or Java.

With the industry adoption of Apache Spark, a leading Scala framework for cloud computing and Big Data, Scala has quickly become popular among Big Data professionals. If you are going for an interview for any of the Big Data job openings that require Apache Spark experience then you should prepare for Scala interview questions as well because Spark is written in Scala.

In this article, I am going to share some fundamental Scala language and Functional Programming questions which are useful for both Java and Big Data professionals, both newcomers and experienced programmers. 

There is also a good demand for Scala developers on startups as Scala programmers are very few as compared to Java professionals and they are also considered best programmers, thanks to the difficult learning curve of Scala. They are also fetching very good salaries, somewhere in the range of $100K to $120K, depending on your skill and experience.

30 Scala Interview Questions and Answers for Experienced Java Programmers

Here is my list of some 20 odd questions from Scala programming and language in general. These are collected from various sources including friends and colleagues. It is mostly for Java developers who are learning Scala or have some experience working in Scala, looking for a development job in Scala. Since the demand of Scala developers is on the rise, with a preference for experienced Java programmers, you could use this list to prepare for telephonic and screening rounds of interviews.

1. What is the latest version of Scala?
This is a simple question to check whether you keep yourself up-to-date with the latest information about Scala or not. If you have not been using Scala actively and don't know the answer then you can say that you have used a certain Scala version. Though, the current version of Scala is Scala 3.2.1, which also requires Java 8. Older Scala versions are compatible with Java 6 and above.

2. Who is the author of Scala Programming language?
This is another basic question about Scala to check your general knowledge about Scala. It is designed by Martin Oderskey, a German computer scientist. He also teaches a course, Functional Programming Principles in Scala and Functional Program Design in Scala on Coursera.

3. What is the difference between val and var in Scala?
The val keyword stands for value and var stands for variable. You can use keyword val to store values, these are immutable, and cannot change once assigned. On the other hand, keyword var is used to create variables, which are values that can change after being set. If you try to modify a val, the compiler will throw an error. It is similar to the final variable in Java or const in C++.

4. What is the difference between == in Java and Scala?
Scala has more intuitive notion of equality. The == operator will automatically run the instance's equals method, rather than doing Java style comparison to check that two objects are actually the same reference. By the way, you can still check for referential equality by using eq method. In short, Java == operator compare references while Scala calls the equals() method. You can also read the difference between == and equals() in Java to learn more about how they behave in Java, here.

5. How to you create Singleton classes in Scala?
Scala introduces a new object keyword, which is used to represent Singleton classes. These are the class with just one instance and their method can be thought of as similar to Java's static methods. Here is a Singleton class in Scala:

package test

object Singleton{
  def sum(l: List[Int]): Int = l.sum

This sum method is available globally, and can be referred to, or imported, as the test.Singleton.sum. A singleton object in Scala can also extend classes and traits.

6. Which books you have read on Scala so far?
This is a general question to check how did you learn Scala, did you read a book or documentation or tutorial etc. It's best to name the book you have read on Scala e.g. I have read Programming in Scala by Martin Odersky and Functional Programming in Scala 1st Edition by Paul Chiusano. 

If you have not read any book then just say you have not read any book yet and like to read Scala documentation or planning to read a book etc. 

The most important thing is, to be honest, don't name a book if you have not read it yet. On a different note, try reading a good book on Scala, Martin Odersky's Programming in Scala: Updated for Scala 2.12 is a good starting point.

Best book to learn Scala language

7. Which keyword is used to define a function in Scala?
A function is defined in Scala using the def keyword. This may sound familiar to Python developers as Python also uses def to define a function.

8. What is the use of App class in Scala?
Scala provides a helper class, called App, that provides the main method. Instead of writing your own main method, classes can extend App class to produce concise and executable applications in Scala as shown in the following example:

object Main extends App {
  Console.println("Hello Scala: " + (args aString ", "))

Here, object Main inherits the main method of App trait and args returns the current command-line arguments as an array, similar to String[] args in Java main method.

9. What's the difference between the following terms and types in Scala: 'Nil', 'Null', 'None', and 'Nothing' in Scala?
Answer: Even though they look similar, there are some subtle differences between them, let's see them one by one:
  • Nil represents the end of a List.
  • Null denotes the absence of value but in Scala, more precisely, Null is a type that represents the absence of type information for complex types that are inherited from AnyRef. It is different than null in Java. 
  • None is the value of an Option if it has no value in it.
  • Nothing is the bottom type of the entire Scala type system, incorporating all types under AnyVal and AnyRef. Nothing is commonly used as a return type from a method that does not terminate normally and throws an exception
Scala functional programming interview questions with answers

10. What is the difference between an object and a class in Scala?
An object is a singleton instance of a class. It does not need to be instantiated by the developer. If an object has the same name that a class, the object is called a companion object.

11. What is the difference between a trait and an abstract class in Scala?
Here are some key differences between a trait and an abstract class in Scala:
  • A class can inherit from multiple traits but only one abstract class.
  • Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. For example, you can’t say trait t(i: Int) {}; the i parameter is illegal.
  • Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. On the other hand, Traits are fully interoperable only if they do not contain any implementation code. See here to learn more about Abstract class in Java and OOP. 

12. What is the difference between a call-by-value and call-by-name parameter?
The main difference between a call-by-value and a call-by-name parameter is that the former is computed before calling the function, and the latter is evaluated when accessed.

13. What is the case class in Scala?
A case class is a special class definition, which works just like a regular Scala class but the compiler creates equals() and toString() methods, as well as immutable access to the field of the class. You can construct a case class instance without using the new keyword.

One more benefit of the case classes is that instances can be decomposed into their constructed fields and can be used in pattern matching. Here is an example of case class hierarchy in Scala, which consists of an abstract superclass Vehicle and two concrete case classes Car and Bike

abstract class Vehicle
case class Car(brand: String) extends Vehicle
case class Bike(brand: String, price: long) extends Vehicle

Instantiating a case class is easy because you don’t need to use the new keyword

val myCar = Car("BMW")

The constructor parameters of case classes are treated as public values and can be accessed directly e.g. myCar.brand will give you "BMW".

Here is another example of traits in Scala using case classes:

Top 30 Scala Interview Questions and Answers for experienced

14. What is the difference between a Java method and a Scala function?
Scala function can be treated as a value. It can be assigned to a val or var, or even returned from another function, which is not possible in Java. Though Java 8 brings lambda expression which also makes function as a first class object, which means you can pass a function to a method just like you pass an object as an argument. See here to learn more about the difference between Scala and Java.

15. What is the difference between a Java future and a Scala future?
Even though both Java and Scala's Future object provides asynchronous computation, but there is a subtle difference between them on how you retrieve the result of the computation. Java's Future (java.util.concurrent.Future) requires that you access the result via a blocking get method. 

Although you can call isDone() method to find out if a Java Future has been completed before calling get, thereby avoiding any blocking, you must wait until the Java Future has completed before proceeding with any computation that uses the result. 

With scala.concurrent.Future you can attach callbacks for completion (success/failure) or simply map it and chain multiple Futures together in a monadic fashion without blocking.

16. What is Companion Object in Scala?
If an object has the same name that a class, the object is called a companion object. A companion object has access to methods of private visibility of the class, and the class also has access to private methods of the object. Doing the comparison with Java, companion objects hold the "static methods" of a class. Just remember that the companion object has to be defined in the same source file that the class. You should also know that Scala classes cannot have static variables or methods. We commonly use Companion Objects for Factories.

17. What is tail recursion in Scala? What is the benefit?
A function is called tail recursive if the recursive call is the last operation in the function; the method does not rely on the result of the recursive call for any more computation. The most important benefit of the tail recursive function is that compiler can rewrite the method in an iterative fashion, similar to a while loop with mutable state. This allows long, deep recursion without taking too much of stack memory that could result in StackOverFlowError

Unfortunately, Java compiler doesn't support tail call optimization but Scala compiler does. In Scala, you can annotate a function with @tailrec to inform the compiler that this particular method is tail recursive. If the compiler cannot make the function tail recursive, it will throw an error.

18. What is "traits" in Scala?
Traits are basically Scala's workaround for the JVM not supporting multiple class inheritance.  Here is an example of traits in Scala:

trait Car {
  val brand: String

trait Costly{
  val cost: Int 

trait Milege{
  val milege: Int

class Audi extends Car with Shiny with Miles{
  val brand = "Audi"
  val cost = 140000
  val milege = 20

19. What is Akka, Play, and Sleek in Scala?
Akka is a concurrency framework in Scala which uses Actor based model for building highly concurrent, distributed, and resilient message-driven applications on the JVM. It uses high-level abstractions like Actor, Future, and Stream to simplify coding for concurrent applications. 

It also provides load balancing, routing, partitioning, and adaptive cluster management. If you are interested in learning Akka, I suggest reading Akka in Action and Akka documentation, both are great resources to learn Akka.

Play is another Scala framework to build web applications in both Java and Scala. The PlayFramework is based on a lightweight, stateless, web-friendly architecture. It is built on Akka, Play provides predictable and minimal resource consumption (CPU, memory, threads) for highly-scalable applications.

Slick is a modern database query and access library for Scala. It allows you to work with stored data almost as if you were using Scala collections while at the same time giving you full control over when a database access happens and which data is transferred. 

You can write your database queries in Scala instead of SQL, thus profiting from the static checking, compile-time safety, and compositionality of Scala. Slick features an extensible query compiler which can generate code for different backends. I have shared 10 best Scala frameworks for development here, you can also check to get more ideas.

20. What is Spark?
Apache Spark is the big data and cloud computing framework written in Scala. The Spark has been engineered from the bottom-up for performance, Spark can be 100x faster than Hadoop for large-scale data processing by exploiting in-memory computing and other optimizations. 

Spark is also fast when data is stored on disk, and currently, holds the world record for large-scale on-disk sorting. Many developers are now learning Scala for Spark to get into the lucrative Big Data Job Market. 

I recommend joining these online Spark Courses and reading "Advanced Analytics with Spark: Patterns for Learning from Data at Scale" by Sandy Ryza,  Uri Laserson, Sean Owen, and Josh Wills. This book will also teach you how you can use functional programming techniques to solve real-world problems, which is a great skill to have.

Top 20 Scala Interview Questions and Answers

21. What is 'Option' and how is it used in Scala?
The 'Option' in Scala is similar to Optional of Java 8. It is a wrapper type that avoids the occurrence of a NullPointerException in your code by giving you a default value in case the object is null. When you call get() from Option it can return a default value if the value is null. More importantly, Option provides the ability to differentiate within the type system those values that can be nulled and those that cannot be nulled.

22. What is ‘Unit’ and ‘()’ in Scala?
The 'Unit' is a type similar to void in Java. You can say it is a Scala equivalent of the void in Java, while still providing the language with abstraction over the Java platform. The empty tuple '()' is a term representing a Unit value in Scala.

23. How to compile and run a Scala program?
You can use Scala compiler scalac to compile Scala program (similar to javac) and scala command to run them (similar to scala)

24. How to tell Scala to look into a class file for some Java class?
Similar to Java, you can use -classpath argument to include a JAR in Scala's classpath, as shown below
$ scala -classpath jar

Alternatively, you can also use the CLASSPATH environment variable.

25. What is the difference between a normal class and a case class in Scala?
Following are some key differences between a case class and a normal class in Scala:
- case class allows pattern matching on it.
- you can create instances of case class without using the new keyword
- equals(), hashcode() and toString() method are automatically generated for case classes in Scala
- Scala automatically generate accessor methods for all constructor argument

26. What is the difference between Scala and Java packages?
Unlike Java, Scala also supports relative package names.

27. What is the difference between 'concurrency' and 'parallelism'? Name some constructs you can use in Scala to leverage both.
Concurrency is when several computations are executing sequentially during overlapping time periods, while parallelism describes processes that are executed simultaneously. The concepts are often confused because actors can be concurrent and parallel, sometimes simultaneously. For example, Node.js has concurrency via its event loop despite being a single-threaded implementation. Parallel collections are a canonical example of parallelism, but Futures and the Async library can be as well. In short, Concurrency is about avoiding access to mutable states by multiple threads at the same time. Parallelism is taking a single task and breaking it apart to be performed by multiple threads at the same time.

28. What are two ways to make an executable Scala program?
There are two general strategies: you can write a script file and use the interpreter, or you can compile an object that has a main method.

29. What does it mean that Scala is compatible with Java?
The standard Scala backend is a Java Virtual Machine. Scala classes are Java classes and vice versa. You can call the methods of either language from methods in the other one. You can extend Java classes in Scala, and vice versa. The main limitation is that some Scala features do not have equivalents in Java, for example, traits.

Scala Functional Programming Interview Questions

30. What is Monad in Scala?
A monad is an object that wraps another object in Scala. It helps to perform the data manipulation of the underlying object, instead of manipulating the object directly.

31. What are High Order Functions in Scala?
High order functions are functions that can receive or return other functions. Common examples in Scala are the filter, map,  and flatMap functions, which receive other functions as arguments.

32. What is a Closure in Scala?
A closure is also known as an anonymous function whose return value depends upon the value of the variables declared outside the function.

33. What is currying in Scala?
Currying is a technique to transform a function that takes multiple arguments into a function that takes a single argument. There is some feature which is inspired by other functional programming languages like Haskell and lisp. 

If you want to learn more about functional programming techniques in Scala, I suggest you read Paul Chiusano and RĂșnar Bjarnason's Functional Programming in Scala 1st edition. It is one of the best books to learn Functional Programming regardless of language. This book teaches you both Scala and Functional Programming through examples and exercises where you use key features of Scala by yourself.

best book to learn Scala and Functional programming

That's all about some of the frequently asked Scala interview questions and answers. If you are going for a Job interview that requires you to work on both Java and Scala then these questions can certainly help you to get familiar with key concepts. 

Though, they barely touch the surface of what Scala offers and what you can do with functional programming. This is best for a junior Scala developer with a couple of years of experience in Scala but for an experienced Scala programmer, a lot more is expected.

If you are new to Scala or want to learn Scala from scratch, I recommend joining these online Scala Programming courses and reading Martin Odersky's Programming in Scala 3rd edition, which is updated for Scala 2.12 version. Martin is the author of Scala language, so you will not just learn how to use a certain feature in Scala but the motivation and concept behind it as well.


Ch!rag said...

Thank you, Javin for such a wonderful explanation. I consider that this article is not only for an interview but also for getting basic Scala and Java diff.

pedrorijo91 said...

I also wrote a similar post about Scala Interview Questions. We have several similar answers, feel free to have a look and discuss any answer you feel it is not exactly correct:

javin paul said...

Hello @Pedro, I checked your list of Scala questions and answers, they are great, thanks for sharing your knowledge and keep it up.

pcheevers said...

Hi Javin
Loving your work.
Given :
"What is a Closure in Scala?
A closure is also known as an anonymous function whose return value depends upon the value of the variables declared outside the function"

A closure is not created only for anonymous functions. So I think the answer should be amended and reference to anonymous function removed.
What do you think?

Post a Comment