Why I love Scala

I wanted to render a set of spinning number wheels, like the wheels of a slot machine. Each wheel spins for a different length of time, has a different time-offset in the animation loop, and is positioned slightly differently.

I could have done this with a giant chain of if-else statements. Instead I set up some data in an infinite stream, zipped it up, and mapped over it.

// Setup the data for our elements...
lazy val stop: Stream[Float] = 3f #:: stop.map(_ + .5f)
lazy val dt: Stream[Float] = 0f #:: .10f #:: .05f #:: -.05f #:: dt
lazy val dx: Stream[Int] = Stream.from(0, 15)

// I can have as many elements as I want by adjusting this number.
val values = (stop, dt, dx).zipped.take(10)
	
override def render() = {
  time += Gdx.graphics.getDeltaTime()
  
  Gdx.gl.glClearColor(clear.r, clear.g, clear.b, clear.a);
  Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
  batch.begin();
	
  // And render all of them!
  values map { case (stop, offset, dx) => 
    val tex = if (time > stop) w7 else anim.getKeyFrame(time + offset)
    batch.draw(tex, 200 + dx, 200)
  }
  batch.end();
}

Et voilĂ .

The resulting spinning wheel animation.

It's clean. It's concise. And more importantly it was fast to write. Beautiful.

Note: if you're curious, this render loop belongs in a LibGDX app.