The most asked Scala interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.
Updated November 2026 Reviewed by Abhishek Kumar 120 min read
100 Scala interview questions, grouped by level: freshers, intermediate, experienced and coding.
Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
Use the filter bar to practise only the level you are interviewing for, then test yourself with the free Scala quiz.
What is Scala, and why do interviewers ask about it?
Scala is a high‑performance language that seamlessly blends object‑oriented and functional programming. This page collects the most frequently asked Scala interview questions – from basic syntax and collections to advanced type system, implicits, concurrency, and integration with the JVM ecosystem – essential for any backend, big data, or functional programmer.
Why companies hire for Scala
Combines OOP and functional programming on the JVM
Powerful type system with inference and generics
Immutable data structures and functional transformations
Industry adoption in big data (Spark, Kafka, Akka)
Full interoperability with Java libraries and tooling
Expressive syntax that reduces boilerplate
100 shown
Basic Scala Interview Questions for Freshers
12 questions
Start here if you are a fresher or switching to Scala. These fundamentals are asked in almost every first-round and campus interview.
1
How interviewers ask it“Let's start with the basics — how would you explain Scala?”
Quick answerScala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way.
Functional: Functions are first-class citizens
Object-oriented: Every value is an object
Type-safe: Strong static type system
JVM compatible: Runs on Java Virtual Machine
Concurrent: Built-in support for concurrency
Scala
// Hello World in ScalaobjectHelloWorld{
defmain(args: Array[String]): Unit = {
println("Hello, World!")
}
}
// Or using App traitobjectHelloWorldextendsApp{
println("Hello, World!")
}
// Functions in Scala// Function declarationdefadd(a: Int, b: Int): Int = {
return a + b
}
// One-line functiondefsubtract(a: Int, b: Int): Int = a - b
// Function with default parametersdefgreet(name: String = "Guest"): String = {
s"Hello, $name!"
}
// Anonymous function (lambda)val square: Int => Int = (x: Int) => x * x
val double: Int => Int = _ * 2// Higher-order functiondefapplyTwice(f: Int => Int, x: Int): Int = f(f(x))
// Function with multiple parameter lists (currying)defaddCurried(a: Int)(b: Int): Int = a + b
// Function with variable argumentsdefsumAll(numbers: Int*): Int = numbers.sum
// Function with named argumentsdefcreatePerson(name: String, age: Int = 0, city: String = "Unknown"): String = {
s"$name ($age) from $city"
}
// Partial functionval partialAdd: Int => Int = addCurried(5)
// Usage
println(add(5, 3))
println(subtract(10, 4))
println(greet("Alice"))
println(square(4))
println(applyTwice(_ * 2, 5))
println(addCurried(5)(3))
println(sumAll(1, 2, 3, 4, 5))
println(createPerson("Alice", age = 25, city = "NYC"))
Quick answerScala provides standard control flow statements including conditionals, loops, and powerful pattern matching.
If-else: if (condition) ... else ...
For loops: for (i <- 1 to 10) { ... }
For comprehensions: for (x <- list) yield x * 2
While loops: while (condition) { ... }
Pattern matching: value match { case 0 => ... }
Scala
// Control Flow in Scala// If-else statementval age: Int = 25val status: String = if (age < 18) "Minor"elseif (age < 65) "Adult"else"Senior"
println(status)
// For loopfor (i <- 1 to 5) {
println(i)
}
// For loop with collectionval fruits: List[String] = List("apple", "banana", "orange")
for (fruit <- fruits) {
println(fruit)
}
// For comprehensionval doubled: List[Int] = for (i <- 1 to 10) yield i * 2
println(doubled)
// While loopvar i: Int = 1while (i <= 5) {
println(i)
i += 1
}
// Do-while loopvar j: Int = 1do {
println(j)
j += 1
} while (j <= 5)
// Break and continue (using breakable)import scala.util.control.Breaks._
breakable {
for (i <- 1 to 10) {
if (i == 6) breakif (i % 2 == 0) {
// continue - just don't execute rest of loop body// Scala doesn't have continue, use if guard instead
}
println(i)
}
}
// Pattern matching (powerful control flow)val number: Int = 2
number match {
case0 => println("Zero")
case1 => println("One")
case2 => println("Two")
case _ => println("Other")
}
Quick answerScala provides linear algebra operations through custom implementations or the Breeze scientific library.
Matrix multiplication: matMul(A, B)
Transpose: transpose(matrix)
Determinant: determinant(matrix)
Breeze: DenseMatrix, DenseVector
Operations: a * b, a.t, det(a)
Scala
// Linear Algebra in Scala// Matrix operationsdefmatMul(A: Array[Array[Double]], B: Array[Array[Double]]): Array[Array[Double]] = {
val rows = A.length
val cols = B(0).length
val inner = B.length
val result = Array.ofDim[Double](rows, cols)
for (i <- 0 until rows; j <- 0 until cols; k <- 0 until inner) {
result(i)(j) += A(i)(k) * B(k)(j)
}
result
}
deftranspose(matrix: Array[Array[Double]]): Array[Array[Double]] = {
val rows = matrix.length
val cols = matrix(0).length
val result = Array.ofDim[Double](cols, rows)
for (i <- 0 until rows; j <- 0 until cols) {
result(j)(i) = matrix(i)(j)
}
result
}
defdeterminant(matrix: Array[Array[Double]]): Double = {
val n = matrix.length
if (n == 1) return matrix(0)(0)
if (n == 2) return matrix(0)(0) * matrix(1)(1) - matrix(0)(1) * matrix(1)(0)
var det = 0.0for (j <- 0 until n) {
val subMatrix = Array.ofDim[Double](n - 1, n - 1)
for (i <- 1 until n; k <- 0 until n if k != j) {
subMatrix(i - 1)(k - (if (k > j) 1else0)) = matrix(i)(k)
}
det += (if (j % 2 == 0) 1else-1) * matrix(0)(j) * determinant(subMatrix)
}
det
}
// Vector operationsdefvectorAdd(a: Array[Double], b: Array[Double]): Array[Double] = {
a.zip(b).map { case (x, y) => x + y }
}
defdotProduct(a: Array[Double], b: Array[Double]): Double = {
a.zip(b).map { case (x, y) => x * y }.sum
}
defnorm(a: Array[Double]): Double = {
sqrt(a.map(x => x * x).sum)
}
// Using Breeze/*
import breeze.linalg._
val A = DenseMatrix((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 10.0))
val B = DenseMatrix((1.0), (2.0), (3.0))
val product = A * B
val transposed = A.t
val det = det(A)
val inv = inv(A)
*/// UsagevalA = Array(
Array(1.0, 2.0, 3.0),
Array(4.0, 5.0, 6.0),
Array(7.0, 8.0, 10.0)
)
valB = Array(Array(1.0), Array(2.0), Array(3.0))
val product = matMul(A, B)
val transposed = transpose(A)
val det = determinant(A)
val v1 = Array(1.0, 2.0, 3.0)
val v2 = Array(4.0, 5.0, 6.0)
println(s"Matrix product: ${product.map(_.mkString(", ")).mkString("; ")}")
println(s"Transpose: ${transposed.map(_.mkString(", ")).mkString("; ")}")
println(s"Determinant: $det")
println(s"Dot product: ${dotProduct(v1, v2)}")
println(s"Norm: ${norm(v1)}")
Quick answerScala performance can be optimized through tail recursion, lazy evaluation, specialization, and compiler flags.
Tail recursion: @tailrec
Lazy evaluation: lazy val, view
Specialization: @specialized
Inlining: @inline
Compiler flags: -optimise, -Xdisable-assertions
Scala
// Performance Optimization in Scala// Performance tips// 1. Use immutable collections when possibleval immutableList = List(1, 2, 3, 4, 5)
// 2. Use tail recursiondefsumTailRec(list: List[Int], acc: Int = 0): Int = {
list match {
caseNil => acc
case head :: tail => sumTailRec(tail, acc + head)
}
}
// 3. Use lazy evaluationlazyval expensiveComputation = {
Thread.sleep(1000)
42
}
// 4. Use view for lazy transformationsval numbers = (1 to 1000000).view.map(_ * 2).filter(_ % 2 == 0)
// 5. Use specialization for performance-critical codeimport scala.annotation.tailrec
import scala.specialized
deffastSum[@specialized(Int, Long, Double) T](list: List[T])(implicit num: Numeric[T]): T = {
list.foldLeft(num.zero)(num.plus)
}
// 6. Use while loop when neededdefsumWhile(arr: Array[Int]): Int = {
var i = 0var sum = 0while (i < arr.length) {
sum += arr(i)
i += 1
}
sum
}
// 7. Use mutable collections for performanceimport scala.collection.mutable.ArrayBufferval buffer = ArrayBuffer.empty[Int]
for (i <- 0 until 1000000) {
buffer += i
}
// 8. Use String interpolation carefullydefbuildString(name: String, age: Int): String = {
s"Name: $name, Age: $age"
}
// 9. Use value classes to avoid allocationclassWrapper(val value: Int) extendsAnyVal// 10. Use @inline annotation for small methodsimport scala.annotation.inline
@inlinedefadd(a: Int, b: Int): Int = a + b
// 11. Use parallel collections for CPU-bound tasksval parallelResult = (1 to 1000000).par.map(_ * 2).toList
// 12. Profile with VisualVM or JProfiler// Run with -XX:+PrintGCDetails -XX:+PrintGCTimeStamps// 13. Use -optimise compiler flag// scalac -optimise YourFile.scala// 14. Use -Xdisable-assertions for production// scalac -Xdisable-assertions YourFile.scala// 15. Use -Xelide-below for debug levels// scalac -Xelide-below 0 YourFile.scala
Quick answerScala testing is done using ScalaTest, ScalaCheck, and other testing frameworks.
ScalaTest: AnyFlatSpec, Matchers
Assertions: result should be (expected)
Data providers: Table with forAll
ScalaCheck: Property-based testing
Futures: ScalaFutures
Scala
// Testing in Scalaimport org.scalatest.flatspec.AnyFlatSpecimport org.scalatest.matchers.should.Matchersimport org.scalatest.{BeforeAndAfter, BeforeAndAfterAll}
import org.scalatest.concurrent.ScalaFutures// Basic testclassMathTestextendsAnyFlatSpecwithMatchers{
"A calculator" should "add two numbers" in {
val result = 2 + 2
result should be (4)
}
it should "subtract two numbers" in {
val result = 10 - 3
result should be (7)
}
}
// Test with floating pointclassFloatTestextendsAnyFlatSpecwithMatchers{
"Floating point" should "be approximately equal" in {
val result = 0.1 + 0.2
result should be (0.3 +- 0.001)
}
}
// Test with exceptionsclassExceptionTestextendsAnyFlatSpecwithMatchers{
"Division by zero" should "throw exception" in {
an [ArithmeticException] should be thrownBy {
10 / 0
}
}
}
// Test with collectionsclassListTestextendsAnyFlatSpecwithMatchers{
val list = List(1, 2, 3, 4, 5)
"A list" should "have correct length" in {
list should have length 5
}
it should "contain specific elements" in {
list should contain (3)
}
it should "be sorted" in {
list shouldBe sorted
}
}
// Test with fixturesclassFixtureTestextendsAnyFlatSpecwithMatcherswithBeforeAndAfter{
var value: Int = 0
before {
value = 42
}
after {
value = 0
}
"A fixture" should "be set up" in {
value should be (42)
}
}
// Test with data providers (tables)classTableTestextendsAnyFlatSpecwithMatchers{
val additionData = Table(
("a", "b", "expected"),
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
(5, -3, 2)
)
forAll(additionData) { (a, b, expected) =>
s"Adding $a and $b" should s"be $expected" in {
val result = a + b
result should be (expected)
}
}
}
// Test with Property-based testing (ScalaCheck)import org.scalacheck.Propertiesimport org.scalacheck.Prop.forAll
objectMathPropsextendsProperties("Math") {
property("addition is associative") = forAll { (a: Int, b: Int, c: Int) =>
(a + b) + c == a + (b + c)
}
}
// Test with ScalaFuturesimport scala.concurrent.{Future, Await}
import scala.concurrent.duration._
classFutureTestextendsAnyFlatSpecwithMatcherswithScalaFutures{
implicitval patience: PatienceConfig = PatienceConfig(timeout = 5.seconds)
"A future" should "complete successfully" in {
val future = Future.successful(42)
whenReady(future) { result =>
result should be (42)
}
}
}
// Running tests// sbt test// sbt testOnly MathTest// Using scalatest with sbt// in build.sbt:// libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.15" % Test
Quick answerScala debugging is done through logging, assertions, and IDEs with breakpoint support.
println: println("debug")
Logging: logger.info("message")
Assertions: assert(condition), require(condition)
Try: Try(expression)
IDE debugger: IntelliJ IDEA, Eclipse
Scala
// Debugging in Scala// Using println for debuggingdefdebugFunction(x: Int): Int = {
println(s"Entering function with x = $x")
val result = x * 2
println(s"Result = $result")
result
}
debugFunction(5)
// Using log4j for logging// libraryDependencies += "org.apache.logging.log4j" %% "log4j-api-scala" % "12.0"/*
import org.apache.logging.log4j.scala.Logging
class MyClass extends Logging {
def doSomething(): Unit = {
logger.info("Doing something")
logger.debug("Debug information")
logger.error("Error occurred")
}
}
*/// Using Scala's logging (built-in)import scala.util.logging.LoggedobjectLoggerextendsLogged{
defprocess(): Unit = {
log("Processing started")
log("Processing completed")
}
}
// Using assertdefassertExample(x: Int): Unit = {
assert(x > 0, "x must be positive")
println(s"x is positive: $x")
}
// Using requiredefrequireExample(x: Int): Unit = {
require(x > 0, "x must be positive")
println(s"x is positive: $x")
}
// Using assumedefassumeExample(x: Int): Unit = {
assume(x > 0, "x must be positive")
println(s"x is positive: $x")
}
// Using StackTracetry {
thrownewException("Something went wrong")
} catch {
case e: Exception =>
println(s"Error: ${e.getMessage}")
e.printStackTrace()
}
// Using scala.util.Try for debuggingimport scala.util.{Try, Success, Failure}
defdivideWithTry(a: Int, b: Int): Try[Int] = {
Try(a / b)
}
divideWithTry(10, 2) match {
caseSuccess(value) => println(s"Result: $value")
caseFailure(e) => println(s"Error: ${e.getMessage}")
}
// Using JVM debugging flags// -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005// Using ScalaTest's Debugger// Run tests with -Dtest.debug=true// Using SBT console for interactive debugging// sbt console// :load MyScript.scala// Using IntelliJ IDEA debugger// Set breakpoints and run in debug mode// Using VisualVM for profiling// jvisualvm// Using JConsole for monitoring// jconsole// Using -Xprint:typer for compiler debugging// scalac -Xprint:typer MyFile.scala// Using -Ydebug for debug information// scalac -Ydebug MyFile.scala
Quick answerFind the maximum value using max, iteration, or recursion.
Built-in: arr.max
Manual: var max = arr(0); for (i <- 1 until arr.length) { if (arr(i) > max) max = arr(i) }
Recursive: if (arr.isEmpty) null else ...
Reduce: arr.reduce(_ max _)
Scala
// Find max in arraydeffindMax(arr: Array[Int]): Int = arr.max
deffindMaxManual(arr: Array[Int]): Int = {
if (arr.isEmpty) thrownewIllegalArgumentException("Array is empty")
var max = arr(0)
for (i <- 1 until arr.length) {
if (arr(i) > max) max = arr(i)
}
max
}
deffindMaxRecursive(arr: Array[Int], index: Int = 0, max: Int = Int.MinValue): Int = {
if (index >= arr.length) max
else findMaxRecursive(arr, index + 1, if (arr(index) > max) arr(index) else max)
}
val arr = Array(1, 5, 3, 9, 2)
println(s"Array: ${arr.mkString(", ")}")
println(s"Max: ${findMax(arr)}")
println(s"Max (manual): ${findMaxManual(arr)}")
println(s"Max (recursive): ${findMaxRecursive(arr)}")
Quick answerCalculate factorial using recursion or iteration.
Recursive: if (n <= 1) 1 else n * factorial(n - 1)
Iterative: for (i <- 2 to n) { result *= i }
Tail recursive: def fact(n: Int, acc: Int = 1): Int = if (n <= 1) acc else fact(n - 1, acc * n)
Edge cases: 0! = 1
Scala
// Factorialdeffactorial(n: Int): Int = {
if (n <= 1) 1else n * factorial(n - 1)
}
deffactorialIterative(n: Int): Int = {
var result = 1for (i <- 2 to n) {
result *= i
}
result
}
deffactorialTail(n: Int, acc: Int = 1): Int = {
if (n <= 1) acc
else factorialTail(n - 1, acc * n)
}
val n = 5
println(s"Factorial of $n:")
println(s"Recursive: ${factorial(n)}")
println(s"Iterative: ${factorialIterative(n)}")
println(s"Tail recursive: ${factorialTail(n)}")
Quick answerCalculate Fibonacci numbers using recursion, iteration, or memoization.
Recursive: if (n <= 1) n else fib(n - 1) + fib(n - 2)
Iterative: var a = 0; var b = 1; for (_ <- 2 to n) { val c = a + b; a = b; b = c }
Memoized: val cache = mutable.Map.empty[Int, Int]
Time: O(n) iterative
Scala
// Fibonaccideffibonacci(n: Int): Int = {
if (n <= 1) n
else fibonacci(n - 1) + fibonacci(n - 2)
}
deffibonacciIterative(n: Int): Int = {
if (n <= 1) n
else {
var a = 0var b = 1for (_ <- 2 to n) {
val c = a + b
a = b
b = c
}
b
}
}
deffibonacciMemoized(n: Int): Int = {
import scala.collection.mutable.Mapval cache = Map.empty[Int, Int]
deffib(n: Int): Int = {
if (n <= 1) n
elseif (cache.contains(n)) cache(n)
else {
val result = fib(n - 1) + fib(n - 2)
cache(n) = result
result
}
}
fib(n)
}
val n = 10
println(s"Fibonacci of $n:")
println(s"Recursive: ${fibonacci(n)}")
println(s"Iterative: ${fibonacciIterative(n)}")
println(s"Memoized: ${fibonacciMemoized(n)}")
Quick answerPrint numbers with FizzBuzz logic using conditional statements or pattern matching.
If-else: if (i % 15 == 0) "FizzBuzz" else if ...
Pattern matching: (i % 3 == 0, i % 5 == 0) match { case (true, true) => ... }
List: (1 to n).map(...)
Output: println
Scala
// FizzBuzzdeffizzbuzz(n: Int): Unit = {
for (i <- 1 to n) {
if (i % 15 == 0) println("FizzBuzz")
elseif (i % 3 == 0) println("Fizz")
elseif (i % 5 == 0) println("Buzz")
else println(i)
}
}
deffizzbuzzList(n: Int): List[String] = {
(1 to n).map { i =>
if (i % 15 == 0) "FizzBuzz"elseif (i % 3 == 0) "Fizz"elseif (i % 5 == 0) "Buzz"else i.toString
}.toList
}
deffizzbuzzMatch(n: Int): Unit = {
for (i <- 1 to n) {
(i % 3 == 0, i % 5 == 0) match {
case (true, true) => println("FizzBuzz")
case (true, false) => println("Fizz")
case (false, true) => println("Buzz")
case _ => println(i)
}
}
}
println("FizzBuzz for 15:")
fizzbuzz(15)
println("FizzBuzz list:")
println(fizzbuzzList(15).mkString(", "))
Quick answerFind missing number using sum formula or XOR operation.
Sum: n * (n + 1) / 2 - arr.sum
XOR: xorAll ^ xorArr
Time: O(n)
Edge cases: Empty array
Scala
// Find missing numberdeffindMissing(arr: Array[Int]): Int = {
val n = arr.length + 1val total = n * (n + 1) / 2val sum = arr.sum
total - sum
}
deffindMissingXOR(arr: Array[Int]): Int = {
val n = arr.length + 1var xorAll = 0for (i <- 1 to n) {
xorAll ^= i
}
var xorArr = 0for (value <- arr) {
xorArr ^= value
}
xorAll ^ xorArr
}
val arr = Array(1, 2, 4, 5, 6)
println(s"Missing number: ${findMissing(arr)}")
println(s"Missing number (XOR): ${findMissingXOR(arr)}")
Quick answerSum array elements using sum, manual loop, or recursion.
Built-in: arr.sum
Manual: var sum = 0; for (value <- arr) { sum += value }
Recursive: if (index >= arr.length) 0 else arr(index) + sumRecursive(arr, index + 1)
Empty: Returns 0
Scala
// Sum of arraydefsumArray(arr: Array[Int]): Int = arr.sum
defsumArrayManual(arr: Array[Int]): Int = {
var sum = 0for (value <- arr) {
sum += value
}
sum
}
defsumArrayRecursive(arr: Array[Int], index: Int = 0): Int = {
if (index >= arr.length) 0else arr(index) + sumArrayRecursive(arr, index + 1)
}
val arr = Array(1, 2, 3, 4, 5)
println(s"Array: ${arr.mkString(", ")}")
println(s"Sum: ${sumArray(arr)}")
println(s"Sum (manual): ${sumArrayManual(arr)}")
println(s"Sum (recursive): ${sumArrayRecursive(arr)}")
Quick answerSplit array into chunks using grouped or manual slicing.
Built-in: arr.grouped(size).toArray
Manual: while (i < arr.length) { result += arr.slice(i, math.min(i + size, arr.length)); i += size }
Predicate: chunkByPredicate
Use case: Batch processing
Scala
// Chunk arraydefchunkArray[T](arr: Array[T], size: Int): Array[Array[T]] = {
arr.grouped(size).toArray
}
defchunkArrayManual[T](arr: Array[T], size: Int): Array[Array[T]] = {
val result = scala.collection.mutable.ArrayBuffer.empty[Array[T]]
var i = 0while (i < arr.length) {
val end = math.min(i + size, arr.length)
result += arr.slice(i, end)
i += size
}
result.toArray
}
defchunkByPredicate[T](arr: Array[T], predicate: T => Boolean): Array[Array[T]] = {
val result = scala.collection.mutable.ArrayBuffer.empty[Array[T]]
var current = scala.collection.mutable.ArrayBuffer.empty[T]
for (item <- arr) {
if (predicate(item)) {
if (current.nonEmpty) {
result += current.toArray
current.clear()
}
result += Array(item)
} else {
current += item
}
}
if (current.nonEmpty) {
result += current.toArray
}
result.toArray
}
val arr = (1 to 10).toArray
println(s"Original: ${arr.mkString(", ")}")
println("Chunk (size 3):")
val chunks = chunkArray(arr, 3)
chunks.foreach(chunk => println(s"[${chunk.mkString(", ")}]"))
Quick answerImplement bubble sort with optimization to stop early if no swaps occur.
Basic: for (i <- 0 until n - 1) { for (j <- 0 until n - i - 1) { if (arr(j) > arr(j + 1)) { val temp = arr(j); arr(j) = arr(j + 1); arr(j + 1) = temp } } }
Optimized: var swapped = false; for (j <- 0 until n - i - 1) { if (...) { ...; swapped = true } }; if (!swapped) return result
Time: O(n²) worst case
Scala
// Bubble sortdefbubbleSort[T: Ordering](arr: Array[T]): Array[T] = {
val result = arr.clone()
val n = result.length
for (i <- 0 until n - 1) {
for (j <- 0 until n - i - 1) {
if (implicitly[Ordering[T]].gt(result(j), result(j + 1))) {
val temp = result(j)
result(j) = result(j + 1)
result(j + 1) = temp
}
}
}
result
}
defbubbleSortOptimized[T: Ordering](arr: Array[T]): Array[T] = {
val ord = implicitly[Ordering[T]]
val result = arr.clone()
val n = result.length
for (i <- 0 until n - 1) {
var swapped = falsefor (j <- 0 until n - i - 1) {
if (ord.gt(result(j), result(j + 1))) {
val temp = result(j)
result(j) = result(j + 1)
result(j + 1) = temp
swapped = true
}
}
if (!swapped) return result
}
result
}
val arr = Array(5, 3, 8, 4, 2, 7, 1, 6)
println(s"Original: ${arr.mkString(", ")}")
println(s"Bubble sort: ${bubbleSort(arr).mkString(", ")}")
println(s"Bubble sort optimized: ${bubbleSortOptimized(arr).mkString(", ")}")
Compose: def compose[T](fns: (T => T)*): T => T = fns.reduceLeft((f, g) => x => g(f(x)))
Use case: Function chaining
Scala
// Pipe functiondefpipe[T](value: T, fns: (T => T)*): T = {
fns.foldLeft(value)((acc, fn) => fn(acc))
}
defcompose[T](fns: (T => T)*): T => T = {
fns.reduceLeft((f, g) => x => g(f(x)))
}
val double: Int => Int = _ * 2val addTen: Int => Int = _ + 10val square: Int => Int = x => x * x
val result = pipe(5, double, addTen, square)
println(s"Pipe: $result")
val process = compose(double, addTen, square)
println(s"Compose: ${process(5)}")
Quick answerImplement compose for right-to-left function composition.
Method: def composeAlt[T](fns: (T => T)*): T => T = fns.reduceRight((f, g) => x => f(g(x)))
With logging: composeWithLogging
Direction: Right to left
Scala
// Compose functiondefcomposeAlt[T](fns: (T => T)*): T => T = {
fns.reduceRight((f, g) => x => f(g(x)))
}
defcomposeWithLogging[T](fns: (T => T)*): T => T = {
fns.reduceRight { (f, g) =>
x => {
val result = f(g(x))
println(s"Intermediate: $result")
result
}
}
}
val double: Int => Int = _ * 2val addTen: Int => Int = _ + 10val square: Int => Int = x => x * x
val composed = composeAlt(double, addTen, square)
println(s"Composed: ${composed(5)}")
val composedWithLogging = composeWithLogging(double, addTen, square)
println(s"Composed with logging: ${composedWithLogging(5)}")
Quick answerImplement memoization using mutable Map cache.
Method: def memoize[T, R](fn: T => R): T => R = { val cache = mutable.Map.empty[T, R]; (arg: T) => cache.getOrElseUpdate(arg, fn(arg)) }
Multiple args: memoizeMultiple
Use case: Expensive functions
Scala
// Memoizationdefmemoize[T, R](fn: T => R): T => R = {
val cache = scala.collection.mutable.Map.empty[T, R]
(arg: T) => {
cache.getOrElseUpdate(arg, fn(arg))
}
}
defmemoizeMultiple[T, R](fn: T => R): T => R = {
val cache = scala.collection.mutable.Map.empty[T, R]
(arg: T) => {
if (cache.contains(arg)) cache(arg)
else {
val result = fn(arg)
cache(arg) = result
result
}
}
}
// Fibonacci with memoizationval fib: Int => Int = memoize { n =>
if (n <= 1) n
else fib(n - 1) + fib(n - 2)
}
val start = System.currentTimeMillis()
println(s"Fibonacci(35): ${fib(35)}")
val time1 = System.currentTimeMillis() - start
println(s"Time: ${time1}ms")
val start2 = System.currentTimeMillis()
println(s"Fibonacci(35) again: ${fib(35)}")
val time2 = System.currentTimeMillis() - start2
println(s"Time: ${time2}ms")
Quick answerImplement once function that ensures a function is called only once.
Method: def once[T, R](fn: T => R): T => R = { var called = false; var result: Option[R] = None; (arg: T) => { if (!called) { called = true; result = Some(fn(arg)) }; result.get } }
With reset: onceWithReset
Scala
// Once functiondefonce[T, R](fn: T => R): T => R = {
var called = falsevar result: Option[R] = None
(arg: T) => {
if (!called) {
called = true
result = Some(fn(arg))
}
result.get
}
}
defonceWithReset[T, R](fn: T => R): (T => R, () => Unit) = {
var called = falsevar result: Option[R] = Noneval reset = () => {
called = false
result = None
}
val fnOnce = (arg: T) => {
if (!called) {
called = true
result = Some(fn(arg))
}
result.get
}
(fnOnce, reset)
}
val initialize = once { (value: Int) =>
println(s"Initialized with $value")
value * 2
}
println(s"First call: ${initialize(10)}")
println(s"Second call: ${initialize(20)}")
val (init, reset) = onceWithReset { (value: Int) =>
println(s"Initialized with $value")
value * 2
}
println(s"First with reset: ${init(10)}")
reset()
println(s"After reset: ${init(20)}")
Quick answerImplement throttle with leading edge execution.
Method: def throttleLeading[T](fn: T => Unit, delay: Long): T => Unit = { var lastCall = 0L; (arg: T) => { val now = System.currentTimeMillis(); if (now - lastCall >= delay) { lastCall = now; fn(arg) } } }
With trailing: throttleWithTrailing
Use case: Scroll events
Scala
// Throttle with leading edgedefthrottleLeading[T](fn: T => Unit, delay: Long): T => Unit = {
var lastCall = 0L
(arg: T) => {
val now = System.currentTimeMillis()
if (now - lastCall >= delay) {
lastCall = now
fn(arg)
}
}
}
defthrottleWithTrailing[T](fn: T => Unit, delay: Long): T => Unit = {
var lastCall = 0L
var pending: Option[T] = Nonevar timer: Option[Thread] = None
(arg: T) => {
val now = System.currentTimeMillis()
if (now - lastCall >= delay) {
lastCall = now
fn(arg)
} else {
pending = Some(arg)
if (timer.isEmpty) {
val remaining = delay - (now - lastCall)
val thread = newThread {
overridedefrun(): Unit = {
Thread.sleep(remaining)
timer = None
lastCall = System.currentTimeMillis()
pending.foreach(fn)
pending = None
}
}
timer = Some(thread)
thread.start()
}
}
}
}
val throttled = throttleLeading { (value: Int) =>
println(s"Processing: $value")
} (2000)
println(throttled(1))
println(throttled(2))
Thread.sleep(3000)
println(throttled(3))
Quick answerImplement command pattern with execute, undo, and redo.
Command: class AddCommand(var receiver: Int, value: Int) extends Command { def execute(): Unit = { oldValue = receiver; receiver += value }; def undo(): Unit = { receiver = oldValue } }
History: class CommandHistory { private val history = mutable.ListBuffer.empty[Command]; private var current = 0; def execute(command: Command): Unit = { command.execute(); history.trimEnd(history.length - current); history += command; current += 1 } }
Scala
// Command patterntraitCommand{
defexecute(): Unitdefundo(): Unitdefredo(): Unit
}
classAddCommand(var receiver: Int, value: Int) extendsCommand{
privatevar oldValue = receiver
defexecute(): Unit = {
oldValue = receiver
receiver += value
}
defundo(): Unit = {
receiver = oldValue
}
defredo(): Unit = {
execute()
}
}
classSubtractCommand(var receiver: Int, value: Int) extendsCommand{
privatevar oldValue = receiver
defexecute(): Unit = {
oldValue = receiver
receiver -= value
}
defundo(): Unit = {
receiver = oldValue
}
defredo(): Unit = {
execute()
}
}
classMacroCommand(commands: Command*) extendsCommand{
defexecute(): Unit = commands.foreach(_.execute())
defundo(): Unit = commands.reverse.foreach(_.undo())
defredo(): Unit = commands.foreach(_.redo())
}
classCommandHistory{
privateval history = scala.collection.mutable.ListBuffer.empty[Command]
privatevar current = 0defexecute(command: Command): Unit = {
command.execute()
history.trimEnd(history.length - current)
history += command
current += 1
}
defundo(): Boolean = {
if (current > 0) {
current -= 1
history(current).undo()
true
} elsefalse
}
defredo(): Boolean = {
if (current < history.length) {
history(current).redo()
current += 1true
} elsefalse
}
}
// Usagevar counter = 0val history = newCommandHistoryval add5 = newAddCommand(counter, 5)
val sub3 = newSubtractCommand(counter, 3)
println(s"Initial: $counter")
history.execute(add5)
println(s"After add: $counter")
history.execute(sub3)
println(s"After sub: $counter")
history.undo()
println(s"After undo: $counter")
history.redo()
println(s"After redo: $counter")
val macroCmd = newMacroCommand(add5, add5, sub3)
history.execute(macroCmd)
println(s"After macro: $counter")
Quick answerImplement state pattern with context and state transitions.
Context: class Context { private var state: State = new ReadyState; def setState(state: State): Unit = { this.state = state }; def request(): Unit = { state.handle(this) } }
States: class ReadyState extends State { def handle(context: Context): Unit = { println("Ready"); context.setState(new ProcessingState) } }
Scala
// State patterntraitState{
defhandle(context: Context): Unit
}
classReadyStateextendsState{
defhandle(context: Context): Unit = {
println("Ready: Waiting for input")
context.setState(newProcessingState)
}
}
classProcessingStateextendsState{
defhandle(context: Context): Unit = {
println("Processing: Working on task")
context.setState(newCompletedState)
}
}
classCompletedStateextendsState{
defhandle(context: Context): Unit = {
println("Completed: Task finished")
context.setState(newReadyState)
}
}
classErrorStateextendsState{
defhandle(context: Context): Unit = {
println("Error: Something went wrong")
context.setState(newReadyState)
}
}
classContext{
privatevar state: State = newReadyStateprivateval data = scala.collection.mutable.Map.empty[String, Any]
defsetState(state: State): Unit = {
this.state = state
}
defrequest(): Unit = {
state.handle(this)
}
defsetData(key: String, value: Any): Unit = {
data(key) = value
}
defgetData(key: String): Option[Any] = data.get(key)
}
classStatefulContextextendsContext{
overridedefrequest(): Unit = {
state.handle(this)
setData("last_state", state.getClass.getSimpleName)
}
}
// Usageval context = newContextfor (i <- 1 to 5) {
println(s"Step $i:")
context.request()
}
println("With data:")
val context2 = newStatefulContextfor (i <- 1 to 5) {
context2.setData("step", i)
context2.request()
println(s"Data: ${context2.getData("last_state")}")
}
Quick answerImplement facade pattern for simplifying complex subsystems.
Facade: class Facade { private val subsystemA = new SubsystemA; private val subsystemB = new SubsystemB; private val subsystemC = new SubsystemC; def simpleOperation(): String = subsystemA.operationA(); def complexOperation(): String = s"${subsystemA.operationA()}
${subsystemB.operationB()}
${subsystemC.operationC()}" }
Quick answerImplement builder pattern for constructing complex objects.
Builder: class Builder { private var product = new Product; def reset(): Unit = product = new Product; def buildStepA(): Unit = product.addPart("Part A"); def getResult(): Product = { val result = product; reset(); result } }
Scala
// Builder patternclassProduct{
privateval parts = scala.collection.mutable.ListBuffer.empty[String]
defaddPart(part: String): Unit = parts += part
deflistParts(): String = parts.mkString(", ")
}
classBuilder{
privatevar product = newProductdefreset(): Unit = product = newProductdefbuildStepA(): Unit = product.addPart("Part A")
defbuildStepB(): Unit = product.addPart("Part B")
defbuildStepC(): Unit = product.addPart("Part C")
defgetResult(): Product = {
val result = product
reset()
result
}
}
classDirector(builder: Builder) {
defbuildMinimal(): Unit = {
builder.buildStepA()
}
defbuildFull(): Unit = {
builder.buildStepA()
builder.buildStepB()
builder.buildStepC()
}
defbuildCustom(steps: List[String]): Unit = {
builder.reset()
steps.foreach {
case"A" => builder.buildStepA()
case"B" => builder.buildStepB()
case"C" => builder.buildStepC()
}
}
}
// Usageval builder = newBuilderval director = newDirector(builder)
println("Minimal product:")
director.buildMinimal()
println(builder.getResult().listParts())
println("Full product:")
director.buildFull()
println(builder.getResult().listParts())
println("Custom product:")
builder.buildStepC()
builder.buildStepA()
println(builder.getResult().listParts())
println("Director custom:")
director.buildCustom(List("C", "A", "B"))
println(builder.getResult().listParts())
Quick answerImplement prototype pattern for cloning objects.
Prototype: class Prototype(val data: Any) { def clone(): Prototype = new Prototype(data); def deepClone(): Prototype = { data match { case map: Map[_, _] => val clonedMap = map.map { case (k, v) => (deepCloneValue(k), deepCloneValue(v)) }; new Prototype(clonedMap); case list: List[_] => new Prototype(list.map(deepCloneValue)); case _ => new Prototype(data) } } }
Scala
// Prototype patternclassPrototype(val data: Any) {
defclone(): Prototype = newPrototype(data)
defdeepClone(): Prototype = {
data match {
case map: Map[_, _] =>
val clonedMap = map.map { case (k, v) => (deepCloneValue(k), deepCloneValue(v)) }
newPrototype(clonedMap)
case list: List[_] =>
newPrototype(list.map(deepCloneValue))
case _ => newPrototype(data)
}
}
privatedefdeepCloneValue(value: Any): Any = {
value match {
case p: Prototype => p.deepClone()
case map: Map[_, _] =>
map.map { case (k, v) => (deepCloneValue(k), deepCloneValue(v)) }
case list: List[_] =>
list.map(deepCloneValue)
case _ => value
}
}
}
classMutablePrototype(var data: Any) extendsPrototype(data) {
defsetData(data: Any): Unit = {
this.data = data
}
}
// Usageval original = newPrototype(Map("name" -> "Original", "value" -> 42))
val copy = original.clone()
val deepCopy = original.deepClone()
println(s"Original: ${original.data}")
println(s"Copy: ${copy.data}")
println(s"Deep copy: ${deepCopy.data}")
val mutable = newMutablePrototype(List(1, 2, 3))
println(s"Original data: ${mutable.data}")
mutable.setData(List(4, 5, 6))
println(s"Modified data: ${mutable.data}")
val clonedMutable = mutable.clone()
println(s"Clone data: ${clonedMutable.data}")
Scala is a modern programming language that combines object-oriented programming and functional programming features. It runs on the JVM and is widely used for backend development, big data processing, and distributed applications.
What are the main features of Scala?
Scala features include object-oriented programming, functional programming, immutable collections, type inference, pattern matching, traits, higher-order functions, concurrency support, and JVM compatibility.
What is the difference between Java and Scala?
Java is primarily an object-oriented programming language, while Scala combines object-oriented and functional programming approaches with features like immutable data structures, pattern matching, and concise syntax.
What are traits in Scala?
Traits in Scala are reusable units of behavior similar to interfaces with implementation. They allow multiple inheritance of behavior and are commonly used for code reuse.
What are case classes in Scala?
Case classes are special Scala classes designed for immutable data modeling. They automatically provide features like pattern matching support, equals, hashCode, and toString methods.
What is functional programming in Scala?
Functional programming in Scala focuses on immutable data, pure functions, higher-order functions, recursion, and avoiding side effects to create reliable and maintainable applications.
What are Futures in Scala?
Futures in Scala represent asynchronous computations that may complete successfully or fail in the future. They are commonly used for non-blocking and concurrent programming.
What is Akka framework in Scala?
Akka is a toolkit used for building highly concurrent, distributed, and fault-tolerant applications using the actor model in Scala and JVM environments.
How is Scala used with Apache Spark?
Scala is the primary language of Apache Spark and is widely used for big data processing, distributed computing, data transformation, and analytics applications.
How can I prepare for a Scala interview?
Practice Scala basics, OOP concepts, functional programming, collections, traits, case classes, pattern matching, Futures, Akka, Spark, concurrency, and real-world JVM development scenarios.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.