Paulo Cereda
04/14/2024, 1:49 PMfun grade(x: Int): String = listOf("A", "B", "C", "D").getOrElse((99 - x).div(10)) { "F" }
I am pretty sure there are cooler ways of achieving this (even my maths can be simplified), so I was wondering what would you do in this case. 🙂 Cheerio!Jacob
04/14/2024, 2:07 PMPaulo Cereda
04/14/2024, 3:44 PMfloorEntry
really does the trick!Daniel Pitts
04/14/2024, 4:26 PMfun getGrade(score:Int) = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 70 -> "C"
score >= 60 -> "D"
else -> "F"
}
At least for this use case. tree map etc is overkill for 5 entries, and it kind of hides the intent a little bit.
Also, the example you have given could be written more concisely even outside of kotlin:
public string CheckGrade(int score)
{
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F"
}
No need to use "else" if each branch returns.Jacob
04/14/2024, 4:28 PMJacob
04/14/2024, 4:30 PMDaniel Pitts
04/14/2024, 4:35 PMDaniel Pitts
04/14/2024, 4:36 PMDaniel Pitts
04/14/2024, 4:42 PMval grades get() = sequenceOf(
90 to "A",
80 to "B",
70 to "C",
60 to "D",
Int.MIN_VALUE to "F"
)
fun grade(score: Int) =
grades
.filter { (num, _) -> score > num }
.map { (_, grade) -> grade }
.first()
Adam S
04/15/2024, 11:43 AMgroostav
05/22/2024, 1:40 AMin
operator:
require(score in 0 .. 100) { "score !in 0..100: $score" }
val grade = when(score){
in 0 ..< 60 -> "F"
in 60 ..< 70 -> "D"
in 70 ..< 80 -> "C"
in 80 ..< 90 -> "B"
in 90 .. 100 -> "A"
else -> unreachable()
}