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?
1 Answer 1
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
-
\$\begingroup\$ Thank you very much ! I made a new commit on this applying your tips and a friend's advice. If interested : github.com/CarolineChaudey/KotlinTraining/commit/… \$\endgroup\$CodingMouse– CodingMouse2017年09月12日 13:14:47 +00:00Commented Sep 12, 2017 at 13:14
Explore related questions
See similar questions with these tags.