O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Infinite sequences – Scala streams

We have seen many examples of Scala's list. Lists are sequences. Moreover, lists are strict sequences. Meaning all elements of the list are constructed upfront. However, there are non-strict sequences, whose elements are constructed as needed.

A list is formed by connecting cons cells. There are two cases:

  1. 1 :: Nil

    In this case, the cons cell has a value and the empty list as a tail. This list has only one element. Let's fire up the REPL and try the following snippets:

    scala> 1 :: Nil
    res2: List[Int] = List(1)
    
  2. 1 :: 2 :: Nil

    Here, we have the cons cell having a value and another list as a tail:

    scala> (1 :: (2 :: Nil)).tail
    res11: List[Int] = List(2)
    

A list with three elements looks like the following:

scala> val ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required