Technical Musings

Thoughts, Ideas, and Experimentation

View on GitHub
19 April 2020

Guessing Game in (non-idiomatic) Kotlin

by Timmy Jose

Learning Kotlin as part of getting started with Android development has been fun so far. A fews years back I had evaluated Kotlin using the book, “Kotlin in Action”, and had found it unbearable reading at that point in time.

Looking back, I realise that it was harsh and rash judgment on my part. I recently picked up the book again, and began diligently working through it, and now realise that the book is actually quite well-written and fast-paced. The book itself is not as hefty as some of the other Kotlin books out there.

I still have issues with the speed of the Kotlin compiler itself, and also the fact that it does not work on my custom built-from-source OpenJDK installation. Instead, I had to install OpenJDK 14 just for this purpose.

Anyway, here is a simple program that I wrote, the usual guessing game where the user has to guess the secret number generated by the program (in the closed range 1-100).

The code:

package com.tzj.guessinggame

import java.util.Random
import java.io.BufferedReader
import java.io.InputStreamReader

fun readGuess(reader: BufferedReader): Int? {
  val guess: Int

  try {
    guess = Integer.parseInt(reader.readLine())
  } catch (e: NumberFormatException) {
    return null
  }

  return guess
}

fun main(args: Array<String>) {
  val random = Random()
  val secret = random.nextInt(100) + 1
  var guessCount = 0
  val  reader = BufferedReader(InputStreamReader(System.`in`))

  try {

    gameloop@
    while(true) {
      print("Enter your guess (1-100): ")
      System.out.flush()

      val guess = readGuess(reader);
      if (guess == null) {
        continue@gameloop
      }

      when {
        guess < secret -> {
          println("Too small!")
          guessCount++
          continue@gameloop
        }
        guess > secret -> {
          println("Too big!")
          guessCount++
          continue@gameloop
        }
        else -> {
          guessCount++
          println("You win! You took $guessCount guesses")
          break@gameloop
        }
      }
    }
  } finally {
    reader.close()
  }
}

Of course it’s not idiomatic Kotlin, but I’m getting there - the language is surprisingly very low-friction (and much smoother around the edges from last I remember).

Running it:

~/dev/playground$ kotlinc GuessingGame.kt -include-runtime -d GuessingGame.jar && java -jar GuessingGame.jar
Java HotSpot(TM) 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
Enter your guess (1-100): 50
Too big!
Enter your guess (1-100): 25
Too small!
Enter your guess (1-100): 38
Too small!
Enter your guess (1-100): 44
Too big!
Enter your guess (1-100): 41
Too small!
Enter your guess (1-100): 42
Too small!
Enter your guess (1-100): 43
You win! You took 7 guesses

< Home >