Over a million developers have joined DZone.

Rolling Dice in Kotlin

A small tutorial on creating a die rolling API in Kotlin, the hottest new language on the JVM.

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

A little more than 2 years ago, I wrote a post on how you could create a die-rolling API in Scala.

As I’m more and more interested in Kotlin, let’s do that in Kotlin.

At the root of the hierarchy lies the Rollable interface:

interface Rollable<T> {
    fun roll(): T
}

The base class is the Die:

open class Die(val sides: Int): Rollable<Int> {

    init {
        val random = new SecureRandom()
    }

    override fun roll() = random.nextInt(sides)
}

Now let’s create some objects:

object d2: Die(2)
object d3: Die(3)
object d4: Die(4)
object d6: Die(6)
object d10: Die(10)
object d12: Die(12)
object d20: Die(20)

Finally, in order to make code using Die instances testable, let’s change the class to inject the Random instead:

open class Die(val sides: Int, private val random: Random = SecureRandom()): Rollable<Int> {
    override fun roll() = random.nextInt(sides)
}

Note that the random property is private, so that only the class itself can use it, there won’t even be a getter.

The coolest thing about that is that I hacked the above code in 15 minutes in the plane. I love Kotlin :-)

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
scala ,api ,kotlin

Published at DZone with permission of Nicolas Frankel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}