Streams infinitos
Modele datos interminables de forma segura
Streams infinitos es una lección gratuita de Scala for Backend Engineering & Functional Programming en CoddyKit. Esta es la lección 3 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.
Infinity, Safely
A LazyList can describe an infinite sequence because its tail is never computed until demanded. You only ever materialize the prefix you consume.
This lets you model natural numbers, primes, or sensor readings without bounding them up front.
All Natural Numbers
LazyList.from(1) is the infinite sequence 1, 2, 3, ... You can take any finite prefix.
Forcing the whole thing would never finish, so always slice it with take or stop with a predicate.
object Demo extends App {
val nats = LazyList.from(1)
println(nats.take(5).toList)
}from with a Step
LazyList.from(start, step) counts by an interval. Use it for even numbers, ticks, or any arithmetic progression.
The sequence is infinite but each call to take forces only what you ask for.
object Demo extends App {
val evens = LazyList.from(0, 2)
println(evens.take(5).toList)
}Self-Referential Streams
A famous trick: define a LazyList in terms of itself. The Fibonacci sequence can be written by zipping the stream with its own tail.
This works only because the tail stays unevaluated until each cell is pulled.
lazy val fibs: LazyList[Int] =
0 #:: 1 #:: fibs.zip(fibs.tail).map { case (a, b) => a + b }
// fibs(0)=0, fibs(1)=1, fibs(2)=1 ...Running Fibonacci
Let's force a prefix of that self-referential Fibonacci stream.
Each new element is computed from earlier, already-memoized ones, so the whole thing stays efficient as you pull more values.
object Demo extends App {
lazy val fibs: LazyList[Int] =
0 #:: 1 #:: fibs.zip(fibs.tail).map { case (a, b) => a + b }
println(fibs.take(10).toList)
}iterate for Sequences
LazyList.iterate generates an infinite sequence by a step function. Powers, geometric growth, and state machines fit naturally.
Here each element is triple the previous, forever.
object Demo extends App {
val triples = LazyList.iterate(1)(_ * 3)
println(triples.take(6).toList)
}A Prime Sieve
Infinite streams shine for the Sieve of Eratosthenes. Take a head prime, filter its multiples from the rest, and recurse.
The filter is lazy, so primes are produced one at a time as you consume them.
def sieve(s: LazyList[Int]): LazyList[Int] =
s.head #:: sieve(s.tail.filter(_ % s.head != 0))
val primes = sieve(LazyList.from(2))Running the Sieve
Now pull the first ten primes from that infinite sieve.
Only enough of the underlying number stream is forced to yield ten primes, demonstrating demand-driven computation.
object Demo extends App {
def sieve(s: LazyList[Int]): LazyList[Int] =
s.head #:: sieve(s.tail.filter(_ % s.head != 0))
val primes = sieve(LazyList.from(2))
println(primes.take(10).toList)
}Never Force the Whole Thing
Methods that need the entire sequence, like length, toList on an unbounded stream, or foreach without a stop, will hang on an infinite LazyList.
Always bound first with take, takeWhile, or find.
// DON'T: LazyList.from(1).toList // hangs forever
val ok = LazyList.from(1).take(3).toListThe Head-Holding Trap
If a val holds the head of an infinite memoizing LazyList and you consume far into it, every forced cell stays alive, leaking memory.
For long traversals, consume via a method without binding the head, or use an Iterator.
Why Infinite Streams Matter
Infinite streams let you separate generation from consumption. The producer describes an endless rule; the consumer decides how much to realize.
This is a powerful functional pattern for pipelines, simulations, and lazy data sources.
Quick Check
Test your understanding of infinite LazyLists.
Recap
Infinite LazyLists work because the tail is demand-driven: from, iterate, self-referential fibs, and the prime sieve all generate endlessly yet realize only what you consume.
Avoid whole-sequence operations and head-holding. Next, we master taking and filtering lazily.
Preguntas frecuentes
¿La lección «Streams infinitos» es gratis?
Sí — el texto completo de «Streams infinitos» 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 «Streams infinitos»?
Modele datos interminables de forma segura 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 3 de 4.
¿Cuánto tiempo toma la lección «Streams infinitos»?
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.