Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
return a word from a given array in kotlin

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 }
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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()
}
over 4 years ago · Santiago Trujillo Report

0

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;
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!