title: Recursive definition of infinite sequence in Kotlin
body: <p>I'm experimenting with the Kotlin sequences and particular the more complicated ones that are not simple calculations on the previous value. </p>
  
  <p>One example I'd like to define is a sequence of all prime numbers.</p>
  
  <p>An easy way to define the next prime is the next integer that is not divisible by any of the previous primes in the sequence.</p>
  
  <p>In Scala this can be translated to:</p>
  
  <pre><code>def primeStream(s: Stream[Int]): Stream[Int] = s.head #:: primeStream(s.tail filter(_ % s.head != 0))
  val primes = primeStream(Stream.from(2))
  
  // first 20 primes
  primes.take(20).toList 
  </code></pre>
  
  <p>I'm having trouble translating this to Kotlin. In scala it works because you can pass function that returns a sequence that will be lazily evaluated but I can't do the same in Kotlin.</p>
  
  <p>In Kotlin I tried</p>
  
  <pre><code>fun primes(seq: Sequence&lt;Int&gt;):Sequence&lt;Int&gt; = sequenceOf(seq.first()) + primes(seq.drop(1).filter {it % seq.first() != 0})
  val primes = primes(sequence(2) {it + 1})
  
  primes.take(20).toList()
  </code></pre>
  
  <p>But that obviously doesn't work because the function is evaluated straight away and leads to an infinite recursion.</p>