Key Scala Concepts and Common Interview Questions
Scala is a language that seamlessly integrates object-oriented programming (OOP) and functional programming (FP). In the paradigm of functional programming, computation is treated as the evaluation of mathematical functions, avoiding state changes and mutable data.
Key advantages and characteristics include:
- Functions are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions.
- Compared to procedural programming, functional code tends to be more concise, predictable, and easier to test because it avoids side effects.
2. Understanding Closures
A closure is a function whose return value depends on the value of one or more variables declared outside the function. Essentially, a function can capture variables from its surrounding environment and access them even after the enclosing scope has finished execution.
Consider the following example:
def createMultiplier(factor: Double): Double => Double = {
(number: Double) => number * factor
}
// Usage
val triple = createMultiplier(3.0)
val halve = createMultiplier(0.5)
println(triple(10.0)) // Output: 30.0
println(halve(10.0)) // Output: 5.0
Here, createMultiplier returns a function that "closes over" the factor variable.
3. Currying in Scala
Currying is the technique of transforming a function that takes multiple arguments into a chain of functions that each take a single argument. This allows for partial application of function arguments.
For instance, a function performing multiplication can be transformed as follows:
// Standard function with two parameters
def standardMultiply(x: Int, y: Int): Int = x * y
// Curried version
def curriedMultiply(x: Int)(y: Int): Int = x * y
// Applying the first argument to create a new function
val multiplyByFive = curriedMultiply(5) _
println(multiplyByFive(4)) // Output: 20
4. Pattern Matching
Scala's pattern matching is a powerful mechanism for checking a value against a pattern. It is similar to Java's switch statement but far more flexible. It matches patterns against values using the match keyword and case blocks.
val result = value match {
case 1 => "One"
case 2 => "Two"
case 3 => "Three"
case _ => "Default" // Wildcard pattern for handling other cases
}
5. Case Class vs. Regular Class
A case class in Scala is syntactic sugar for a class that is primarily used to model immutible data. It differs from a standard class in several ways:
- Instantiation: The
newkeyword is not required for instantiation because anapplymethod is automatically generated in the companion object. - Immutability: Parameters in a case class are
valby default (immutable), whereas regular class parameters arevarunless specified otherwise. - Auto-generated Methods: Methods like
equals,hashCode,toString, andcopyare automatically provided. - Comparison: Instances of case classes are compared by value structure rather than by reference.
6. Implicit Conversions
A implicit conversion allows the compiler to automatically convert one type to another when an expression does not match the expected type. This is achieved by defining a single-argument function marked with the implicit keyword.
For example, automatically converting an Int to a custom Distance type:
case class Distance(meters: Int)
implicit def intToDistance(n: Int): Distance = Distance(n)
// The compiler automatically applies intToDistance
val d: Distance = 100 // Converted to Distance(100)
7. Companion Objects and Companion Classes
In Scala, a class and an object with the same name defined within the same source file are called companion classes and companion objects.
- Access: They can access each other's private members.
- Singleton: The object acts as a singleton instance, often used for factory methods (
apply) and static utility methods. - Isolation: An object without a same-named class in the same file is called a standalone object.
Example of companion interaction:
class Entity(id: Int) {
private val secretId = id + 1000
def getObjectSecret: String = Entity.hiddenKey // Accessing object's private member
}
object Entity {
private val hiddenKey = "Secret-Key-XYZ"
def revealClassSecret(e: Entity): Int = e.secretId // Accessing class's private member
}
// val e = new Entity(1)
// println(Entity.revealClassSecret(e)) // Output: 1001