Scala
Scalable Language
A JVM language combining object-oriented and functional programming. Developed by Martin Odersky. The core language of Spark, Akka, and Play Framework.
Scalable Language
A JVM language combining object-oriented and functional programming. Developed by Martin Odersky. The core language of Spark, Akka, and Play Framework.
Scala (Scalable Language) is a programming language that runs on the JVM (Java Virtual Machine) and is a hybrid language that naturally combines object-oriented programming (OOP) and functional programming (FP). It is fully compatible with Java while offering a more concise and expressive syntax, so you can use the vast libraries of the Java ecosystem while applying modern programming paradigms.
Scala was designed and released in 2004 by Professor Martin Odersky at EPFL (École Polytechnique Fédérale de Lausanne) in Switzerland. Odersky was a co-designer of the Java compiler javac and Java Generics, and drawing on that experience he set out to create a language that keeps Java's strengths while overcoming its limitations. The name "Scala" is short for "Scalable Language," reflecting the philosophy of a language that scales from small scripts to large distributed systems.
Scala's key features include powerful Type Inference, Pattern Matching, Immutable data structures, Higher-Order Functions, and trait-based mixin inheritance. These features improve both the conciseness and the safety of code. In particular, for-comprehensions, implicit conversions, and Case Classes are regarded as unique features of Scala.
In practice, Scala is most widely used as the core language of Apache Spark, the big data processing framework. The high-performance concurrency framework Akka, the web framework Play Framework, and the build tool SBT are also written in Scala. Global companies such as Twitter, LinkedIn, Netflix, and Airbnb have adopted Scala for large-scale backend systems, and it shows particular strength in distributed processing, streaming data, and microservice architecture.
// Scala 기본 문법 예제
// 불변 변수 (val) vs 가변 변수 (var)
val name: String = "Scala" // 불변 (권장)
var count: Int = 0 // 가변
// 타입 추론 - 타입 명시 생략 가능
val message = "Hello, Scala!" // String으로 추론
val numbers = List(1, 2, 3) // List[Int]로 추론
// 함수 정의
def greet(name: String): String = {
s"Hello, $name!" // 문자열 보간법
}
// 한 줄 함수 (중괄호 생략)
def square(x: Int): Int = x * x
// 익명 함수 (람다)
val double = (x: Int) => x * 2
// 컬렉션 연산 (함수형 스타일)
val nums = List(1, 2, 3, 4, 5)
val evens = nums.filter(_ % 2 == 0) // List(2, 4)
val doubled = nums.map(_ * 2) // List(2, 4, 6, 8, 10)
val sum = nums.reduce(_ + _) // 15
// 메서드 체이닝
val result = nums
.filter(_ > 2)
.map(_ * 10)
.sum // 120
// 케이스 클래스 - 데이터 모델링의 핵심
case class User(
id: Long,
name: String,
email: String,
age: Option[Int] = None // Optional 값
)
// 케이스 클래스는 자동으로 equals, hashCode, toString, copy 제공
val user1 = User(1, "Alice", "alice@example.com", Some(25))
val user2 = user1.copy(name = "Bob") // 불변 업데이트
// Sealed trait로 대수적 데이터 타입 정의 (ADT)
sealed trait PaymentMethod
case class CreditCard(number: String, cvv: String) extends PaymentMethod
case class PayPal(email: String) extends PaymentMethod
case object Cash extends PaymentMethod
// 패턴 매칭 - 타입 안전한 분기 처리
def processPayment(method: PaymentMethod): String = method match {
case CreditCard(num, _) =>
s"Processing credit card ending in ${num.takeRight(4)}"
case PayPal(email) =>
s"Processing PayPal payment for $email"
case Cash =>
"Processing cash payment"
}
// Option 패턴 매칭으로 null 안전 처리
def getUserAge(user: User): String = user.age match {
case Some(age) => s"User is $age years old"
case None => "Age not provided"
}
// 가드 조건과 함께 사용
def categorize(age: Int): String = age match {
case a if a < 13 => "Child"
case a if a < 20 => "Teenager"
case a if a < 65 => "Adult"
case _ => "Senior"
}
// 고차 함수 (Higher-Order Function)
def applyTwice[A](f: A => A, x: A): A = f(f(x))
val result = applyTwice((x: Int) => x + 1, 5) // 7
// for-comprehension (flatMap + map의 문법적 설탕)
case class Order(userId: Long, items: List[String])
val orders = List(
Order(1, List("Apple", "Banana")),
Order(2, List("Orange"))
)
// 모든 주문의 모든 아이템 추출
val allItems = for {
order <- orders
item <- order.items
} yield item // List("Apple", "Banana", "Orange")
// Option과 for-comprehension으로 안전한 연산
def findUser(id: Long): Option[User] = ???
def findOrder(userId: Long): Option[Order] = ???
val userItems: Option[List[String]] = for {
user <- findUser(1)
order <- findOrder(user.id)
} yield order.items // None이 하나라도 있으면 None
// Either로 에러 처리 (함수형 방식)
sealed trait ValidationError
case class InvalidEmail(msg: String) extends ValidationError
case class InvalidAge(msg: String) extends ValidationError
def validateUser(
email: String,
age: Int
): Either[ValidationError, User] = {
if (!email.contains("@"))
Left(InvalidEmail("Email must contain @"))
else if (age < 0)
Left(InvalidAge("Age must be positive"))
else
Right(User(1, "Valid", email, Some(age)))
}
// 커링 (Currying)
def add(x: Int)(y: Int): Int = x + y
val addFive = add(5) _ // 부분 적용된 함수
val eight = addFive(3) // 8
"We're evaluating Scala vs Kotlin as the language for the new microservice. Kotlin has a lower learning curve and many people with Android experience, which helps with hiring. But our team handles a lot of Spark pipelines and uses an Akka-based actor model, so for consistency with the existing codebase I think it makes sense to stay with Scala. Also, if we migrate to Scala 3, the syntax becomes much more concise, which will reduce the learning burden."
"The core advantages of functional programming in Scala are immutability and pure functions. Using immutable data structures eliminates race conditions in concurrent programming at the source, and pure functions guarantee the same output for the same input, making testing and debugging easier. This is also why RDD operations in Spark are all designed as immutable transformations. Also, by using pattern matching and the Option/Either types, you can catch null-related runtime errors at compile time."
"I'd like you to change var to val here and refactor with recursion or fold. In Scala, it is customary to minimize mutable state. Also, if a match expression doesn't handle all cases, the compiler shows a warning, and if you use a sealed trait, the compiler checks the exhaustiveness of the pattern match for you."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Scala supports both OOP and FP and has many complex concepts such as implicits, type classes, and an advanced type system, so it takes considerable time for Java or Python developers to get comfortable. If no one on your team has Scala experience, plan for a 3-6 month learning period. We recommend starting with simple FP patterns and introducing advanced features gradually.
Scala 3 (Dotty) was released in 2021 and made major changes to the syntax and type system. It introduced given/using in place of implicit, a new enum syntax, optional braces, and more. You need to check compatibility with your existing Scala 2 codebase and libraries, and migration may require substantial refactoring. Use Scala 3 for new projects, and for existing projects decide after checking the ecosystem's support status.
Because of Scala's powerful type inference and implicit resolution, compile times can be 2-3 times longer than Java. In large projects, build time affects productivity. Use SBT's incremental compilation, the Bloop compile server, Zinc caching, and so on, and split modules well to minimize unnecessary recompilation.