Guessing Game in Kotlin

This is just a quick post showing the canonical implementation of the Guessing Game in Kotlin. While Kotlin may not have the full-blown Pattern-matching abilities of Rust, it has a pretty powerful switching mechanism (more powerful than that available in D). Here is how the code looks, and a sample run follows thereafter:

import java.util.Random

fun main(args: Array<String>) {
    val secretNumber = Random().nextInt(100)

    println("Welcome to the Guessing Game!\n")

    var guess: Int
    var attempts=0

    while (true) {
        print("Enter your guess (1-100): ")
        guess = readLine()!!.toInt()

        when (guess.compareTo(secretNumber)) {
                -1 -> { println("Too small!"); attempts++ }
                 0 -> { attempts++; println("You win! You took $attempts guesses!"); return }
                 1 -> { println("Too big!"); attempts++ }

Short and elegant, and the availability of free-functions (at least from the user’s perspective) is a great feature! Here’s a test run:

Macushla:Learn Kotlin z0ltan$ kotlinc GuessingGame.kt -include-runtime -d GuessingGame.jar
Macushla:Learn Kotlin z0ltan$ java -jar GuessingGame.jar
Welcome to the Guessing Game!

Enter your guess (1-100): 50
Too big!
Enter your guess (1-100): 25
Too small!
Enter your guess (1-100): 38
Too big!
Enter your guess (1-100): 31
You win! You took 4 guesses!
Guessing Game in Kotlin

One thought on “Guessing Game in Kotlin

Speak your mind!

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s