Scala Overview
Scala is a strong statically typed general-purpose programming language which supports both object-oriented programming and functional programming. Designed to be concise, many of Scala's design decisions are aimed to address criticisms of Java.
Key Features
- JVM Language: Runs on Java Virtual Machine.
- Interoperable: Seamless Java interoperability.
- Type Inference: Compiler can deduce types.
- Immutability: Encourages immutable data structures.
- Pattern Matching: Powerful way to handle different cases.
- Higher-Order Functions: Functions as first-class citizens.
- Concurrent Programming: Built-in support with Akka.
Common Use Cases
Big Data
Apache Spark is written in Scala.
Web Development
With frameworks like Play, Akka HTTP.
Distributed Systems
Using Akka for actor-based concurrency.
Data Engineering
Processing large datasets.
Example Code
// Scala example demonstrating features
// Case class (immutable)
case class Person(name: String, age: Int) {
def greet: String = s"Hello, my name is $name"
}
// Trait (interface)
trait Greeter {
def greet: String
}
// Companion object
object Person {
def defaultPerson: Person = Person("Anonymous", 0)
}
// Using the examples
val alice = Person("Alice", 30)
println(alice.greet)
// Pattern matching
val result = alice match {
case Person("Alice", age) => s"Found Alice who is $age years old"
case _ => "Not Alice"
}
println(result)
// Higher-order function
val numbers = List(1, 2, 3, 4, 5)
val squares = numbers.map(x => x * x)
println(s"Squares: $squares")
// For comprehension
val pairs = for {
n <- numbers
if n % 2 == 0
square = n * n
} yield (n, square)
println(s"Even squares: $pairs")
// Future for async programming
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val futureResult: Future[Int] = Future {
// Simulate computation
Thread.sleep(1000)
42
}
futureResult.onComplete {
case scala.util.Success(value) => println(s"Result: $value")
case scala.util.Failure(exception) => println(s"Error: ${exception.getMessage}")
}
// Thread.sleep(2000) // Wait for future to complete in example