Transformaciones y acciones
Cálculo perezoso
Transformaciones y acciones es una lección gratuita de Scala for Backend Engineering & Functional Programming en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Scala for Backend Engineering & Functional Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Scala for Backend Engineering & Functional Programming incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Two Kinds of Operations
Spark operations split into transformations (build a new dataset, lazy) and actions (trigger computation and return a result or write output).
Lazy Evaluation
Transformations are lazy: they record what to do but run nothing. Spark builds a directed acyclic graph (DAG) of transformations and only executes when an action is called.
map and filter
map transforms each element; filter keeps elements matching a predicate. Both return new RDDs/Datasets and do not run yet.
val nums = sc.parallelize(1 to 10)
val evens = nums.filter(_ % 2 == 0).map(_ * 10)
// nothing computed yetflatMap
flatMap maps each element to zero or more outputs and flattens them — classic for splitting lines into words.
val lines = sc.parallelize(Seq("hello world", "spark rocks"))
val words = lines.flatMap(_.split(" "))Common Actions
Actions trigger execution:
collect— bring all results to the drivercount— number of elementsfirst/take(n)— sample rowsreduce— fold into one value
val total = sc.parallelize(1 to 100).reduce(_ + _)
println(total) // 5050 — runs nowNarrow vs Wide
Narrow transformations (map, filter) need no data movement. Wide transformations (groupByKey, reduceByKey, join) trigger a shuffle across the network.
reduceByKey
On key-value RDDs, reduceByKey aggregates values per key. It combines locally before shuffling, making it more efficient than groupByKey.
val pairs = sc.parallelize(Seq(("a", 1), ("b", 1), ("a", 1)))
val counts = pairs.reduceByKey(_ + _)
// (a, 2), (b, 1)Caching
If a dataset is reused across multiple actions, cache or persist keeps it in memory so it is not recomputed each time.
val cached = sc.parallelize(1 to 1000).filter(_ % 3 == 0).cache()
println(cached.count())
println(cached.sum())DataFrame Transformations
DataFrames have their own lazy transformations: select, where, withColumn, orderBy. Actions like show and collect trigger them.
import org.apache.spark.sql.functions._
val adults = df.where(col("age") >= 18)
.withColumn("adult", lit(true))
adults.show()The Word Count Classic
The canonical Spark job: split lines, map each word to one, reduce by key. Only the final collect runs the pipeline.
val text = sc.textFile("book.txt")
val counts = text.flatMap(_.split(" "))
.map(w => (w, 1))
.reduceByKey(_ + _)
counts.collect().foreach(println)Plain Scala Lazy Analog
A self-contained Scala analog: a lazy view defers work until forced, mirroring Spark's transformation/action split.
object Main {
def main(args: Array[String]): Unit = {
val pipeline = (1 to 10).view.filter(_ % 2 == 0).map(_ * 10) // lazy
val result = pipeline.toList // forces evaluation (action)
println(result)
}
}Quick Check
When does Spark actually execute a chain of map and filter transformations?
Recap
You learned Spark's execution model:
- Transformations are lazy (
map,filter,flatMap,reduceByKey) - Actions trigger work (
collect,count,reduce) - narrow vs wide (shuffle) operations
cacheto reuse results
Next: Spark SQL.
Preguntas frecuentes
¿La lección «Transformaciones y acciones» es gratis?
Sí — el texto completo de «Transformaciones y acciones» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Scala for Backend Engineering & Functional Programming, actualiza a CoddyKit PRO. El curso de Scala for Backend Engineering & Functional Programming incluye 4 lecciones en total.
¿Qué aprenderé en «Transformaciones y acciones»?
Cálculo perezoso Practicas Scala for Backend Engineering & Functional Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Scala for Backend Engineering & Functional Programming?
No se requiere experiencia previa. Scala for Backend Engineering & Functional Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Transformaciones y acciones»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Scala for Backend Engineering & Functional Programming?
Sí. Cada lección de Scala for Backend Engineering & Functional Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- RDDs y DataFrames
- Transformaciones y acciones
- Spark SQL
- Agregaciones