Scala

Programacion funcional en JVM - impulsa Apache Spark para big data con tipado fuerte e interop Java

TL;DR

En resumen: Scala es programación funcional en la JVM - sistema de tipos potente, código conciso y el lenguaje de Spark.

Fortalezas principales:

  • Lo mejor de OOP y FP en un lenguaje
  • Inmutabilidad y funciones puras por defecto
  • Corre en JVM con interoperabilidad Java
  • Impulsa Apache Spark y big data

Philosophy

Scala une dos mundos:

  • Lenguaje escalable - De scripts a sistemas grandes. El nombre lo dice.
  • Funcional primero - Datos inmutables, pattern matching, funciones de orden superior
  • Tipos fuertes - Detectar errores en compilación, no en ejecución
  • Orientado a expresiones - Todo devuelve un valor. Sin statements.

Scala 3 simplificó significativamente el lenguaje. Es más accesible de lo que su reputación sugiere.

Quick Start

Install

# Using Coursier (recommended)
curl -fL https://github.com/coursier/coursier/releases/latest/download/cs-x86_64-pc-linux.gz | gzip -d > cs
chmod +x cs && ./cs setup

# macOS
brew install coursier/formulas/coursier && cs setup

Verify (latest: 3.7.4)

scala -version  # Scala 3.7.4

First Program

Crea hello.scala:

@main def hello() = println("Hello, World!")
scala hello.scala

Scala REPL

scala
scala> 1 + 1
val res0: Int = 2

Language Essentials

Variables & Types

// Immutable (preferred)
val name = "Alice"    // Type inferred
val age: Int = 25     // Explicit type

// Mutable (avoid when possible)
var count = 0
count += 1

// Collections
val list = List(1, 2, 3)
val map = Map("a" -> 1, "b" -> 2)
val tuple = (1, "hello", true)

Control Flow

// Everything is an expression
val status = if age >= 18 then "adult" else "minor"

// Pattern matching (powerful switch)
val result = x match
  case 1 => "one"
  case 2 | 3 => "two or three"
  case n if n > 10 => "big"
  case _ => "other"

// for comprehension
for i <- 1 to 5 do println(i)

// with yield (like map)
val doubled = for i <- List(1, 2, 3) yield i * 2

Functions

// Method
def greet(name: String): String =
  s"Hello, $name!"

// Anonymous function
val add = (a: Int, b: Int) => a + b

// Higher-order function
def apply(f: Int => Int, x: Int): Int = f(x)
apply(_ * 2, 5)  // 10

// Default and named parameters
def greet(name: String, greeting: String = "Hello") =
  s"$greeting, $name!"

greet("Alice", greeting = "Hi")

Classes & Case Classes

// Regular class
class User(val name: String, var age: Int):
  def greet() = s"Hi, I'm $name"

// Case class (immutable data, auto-generated methods)
case class Person(name: String, age: Int)

val p1 = Person("Alice", 25)
val p2 = p1.copy(age = 26)
println(p1 == p2)  // false (value comparison)

// Destructuring
val Person(name, age) = p1

Option & Error Handling

// Option instead of null
val maybe: Option[String] = Some("hello")
val empty: Option[String] = None

maybe.map(_.toUpperCase)     // Some("HELLO")
maybe.getOrElse("default")   // "hello"

// Try for exceptions
import scala.util.{Try, Success, Failure}

Try(parseInt("abc")) match
  case Success(n) => println(n)
  case Failure(e) => println(e.getMessage)

Gotchas

val no significa contenido inmutable

val list = scala.collection.mutable.ListBuffer(1, 2, 3)
list += 4  // OK! Reference is fixed, contents can change

// Use immutable collections for true immutability
val immutable = List(1, 2, 3)

Sintaxis Scala 2 vs Scala 3

// Scala 3 uses indentation-based syntax
def greet(name: String) =
  val msg = s"Hello, $name"
  println(msg)

// Scala 2 uses braces (still works in 3)
def greet(name: String) = {
  val msg = s"Hello, $name"
  println(msg)
}

Conversiones implícitas

// Be careful with implicits - they can be confusing
given Conversion[String, Int] = _.length

val x: Int = "hello"  // 5, but hard to read!

When to Choose

Ideal para:

  • Big Data (Apache Spark)
  • Programación funcional en JVM
  • Modelado de dominios complejos
  • Sistemas de alta concurrencia (Akka)

No ideal para:

  • Apps web simples (usar Go, Node.js)
  • Equipos nuevos en FP
  • Prototipos rápidos (curva de aprendizaje)

Comparación:

AspectoScalaKotlinJava
ParadigmaFP + OOPOOP + FPOOP
AprendizajeDifícilFácilFácil
VerbosidadBajaBajaAlta
EcosistemaSparkAndroidEnterprise

Next Steps

Ecosystem

Build Tools

# sbt (Scala Build Tool)
sbt new scala/scala3.g8   # Create new project
sbt compile               # Compile
sbt run                   # Run
sbt test                  # Test

# scala-cli (simpler for scripts)
scala-cli run hello.scala
  • Big Data: Apache Spark, Flink
  • Web: Play Framework, http4s, ZIO
  • Concurrent: Akka, ZIO, Cats Effect
  • Testing: ScalaTest, MUnit