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?

asked Sep 8, 2017 at 19:20
\$\endgroup\$

1 Answer 1

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

answered Sep 8, 2017 at 21:35
\$\endgroup\$
1

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.