Home > Enterprise >  return a word from a given array in kotlin
return a word from a given array in kotlin

Time:12-17

I am beginner in kotlin (in coding in general) and am trying to get the following sentence: "The 6 sided [randomColor] dice rolled [randomNumber]". Basically the only part I cannot get correctly is the color, I get "kotlin.Unit" instead. The code I am using is below. Many thanks in advance for your help!

fun main() {
    val myFirstDice = Dice(6)
    println ("The ${myFirstDice.numSides} sided ${randomColor()} dice rolled ${myFirstDice.roll()}")
}
class Dice(val numSides: Int){ 
    fun roll(): Int{
        return (1..numSides).random()
    }
}
fun randomColor() {
    val list = listOf("black", "yellow", "green")
    val randomColor = list.shuffled().find { true }
}

CodePudding user response:

I would do it a little bit differently. I would not use shuffled() method, but instead rely on the built-in random() method available since kotlin 1.3 (reference documentation):

fun randomColor(): String {
    val list = listOf("black", "yellow", "green")
    return list.random()
}

CodePudding user response:

You need to return the value of randomColor:

fun randomColor(): String? {
    val list = listOf("black", "yellow", "green")
    val randomColor = list.shuffled().find { true }
    return randomColor;
}
  • Related