title: How to cycle a list infinitely and lazily in Kotlin?
body: <p>I have a list of <code>directions</code> and want to find the next direction when I take a right or left turn. Here is the working code I have:</p>
  
  <pre><code>enum class Turn { R, L }
  enum class Direction { N, E, S, W }
  val directionsInRightTurnOrder = listOf(Direction.N, Direction.E, Direction.S, Direction.W)
  
  private fun calculateNextHeading(heading: Direction, turn: Turn): Direction {
      val currentIndex = directionsInRightTurnOrder.indexOf(heading)
      var nextIndex = currentIndex + if (turn == Turn.R) 1 else -1
      if (nextIndex &gt;= directionsInRightTurnOrder.size)
          nextIndex = directionsInRightTurnOrder.size - nextIndex
      if (nextIndex &lt; 0)
          nextIndex += directionsInRightTurnOrder.size
  
      return directionsInRightTurnOrder.get(nextIndex)
  }
  </code></pre>
  
  <ol>
  <li>However, this would be so much simpler and easier to read if I could take the <code>directionsInRightTurnOrder</code> list and cycle through it infinitely (and lazily). In Clojure, I can do that, using <a href="https://clojuredocs.org/clojure.core/cycle" rel="noreferrer">clojure.core/cycle</a>:</li>
  </ol>
  
  <pre class="lang-clj prettyprint-override"><code>(take 5 (cycle ["a" "b"]))
  # ("a" "b" "a" "b" "a")
  </code></pre>
  
  <ol start="2">
  <li><p>Another thing that would help is if I could look up in a list using a negative index, like in Ruby or Python:</p>
  
  <ul>
  <li><a href="http://rubyquicktips.com/post/996814716/use-negative-array-indices" rel="noreferrer">http://rubyquicktips.com/post/996814716/use-negative-array-indices</a></li>
  <li><a href="https://stackoverflow.com/questions/11367902/negative-index-to-python-list">Negative index to Python list</a></li>
  </ul></li>
  </ol>
  
  <h2>Question:</h2>
  
  <ul>
  <li>Can I do <code>cycle</code> through a list/collection in Kotlin?</li>
  <li>Is there an idiomatic way to do a negative-index-lookup in Kotlin?</li>
  </ul>