4
\$\begingroup\$

I am a Java developer, and I recently gave Kotlin a try. To begin, I did a little exercise I often do when I start a new language, to verify I got the very basics: the more or less game. The code I submit there is working fine, but of course I suspect it may be too much like Java, and I would like you to point to me how I can make my code more Kotlin.

package fr.caro

import java.util.*

fun main(args: Array<String>) {
    val min = 0
    val max = 100
    var nbAttempts = 0
    val random = SplittableRandom()
    val reader = Scanner(System.`in`)
    val goal = random.nextInt(min, max)
    var userGuess: Int

    computerSays("I chose a number between $min and $max")
    do {
        nbAttempts++
        computerSays("What's your guess?")
        userGuess = reader.nextInt()
        if (userGuess > goal) computerSays("less !")
        else if (userGuess < goal) computerSays("more !")
    } while(userGuess != goal)

    computerSays("Congratulation ! You found in $nbAttempts attemps.")
}

fun computerSays(text: String) {
    println("Computer : " + text)
}

PS: I wonder if putting the min and max values in a Pair object would be a good idea?

\$\endgroup\$
1
\$\begingroup\$

When statement

You could replace:

if (userGuess > goal) computerSays("less !")
else if (userGuess < goal) computerSays("more !")

and

computerSays("Congratulation ! You found in $nbAttempts attemps.")

with:

when {
    userGuess > goal -> computerSays("less !")
    userGuess < goal -> computerSays("more !")
    userGuess == goal -> computerSays("Congratulation ! You found in $nbAttempts attemps.")
}

Extension functions

You could write computerSays as:

fun String.outputAsComputer() {
    println("Computer : " + this)
}

then to output Computer: ABC you could just write:

"ABC".outputAsComputer()

Although there are good arguments for and against this, it is more a chance to get used to extension functions

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.