typestar

grade_report.kt in Kotlin

Report cards from a data class roster, a when ladder, and format strings.

// Average each student's scores and print a letter-grade report card.

data class Student(val name: String, val scores: List<Int>)

val ROSTER = listOf(
    Student("Ada", listOf(92, 88, 97)),
    Student("Grace", listOf(84, 91, 78)),
    Student("Alan", listOf(70, 66, 74)),
    Student("Edsger", listOf(58, 67, 61)),
)

fun letter(avg: Double): Char = when {
    avg >= 90 -> 'A'
    avg >= 80 -> 'B'
    avg >= 70 -> 'C'
    avg >= 60 -> 'D'
    else -> 'F'
}

fun main() {
    println("student  avg grade")
    for (s in ROSTER.sortedBy { it.name }) {
        val avg = s.scores.average()
        println("%-8s %4.1f  %c".format(s.name, avg, letter(avg)))
    }
    val classAvg = ROSTER.flatMap { it.scores }.average()
    println("Class average: %.1f".format(classAvg))
}

How it works

  1. Student is a data class; ROSTER holds four of them.
  2. letter maps an average to a grade with a subjectless when.
  3. flatMap pools every score for the class average at the end.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
706
Tokens
232
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 214 seconds.

Type this snippet

Step 2 of 3 in Encore, step 26 of 27 in Language basics.

← Previous Next →