An Example Kotlin Program
fun main() {
val results = mutableListOf<Result>()
while (true) {
print("Name: ")
val name = readln()
if (name.isBlank()) break
var mark: Int?
do {
print("Mark: ")
mark = readln().toIntOrNull()
} while (mark == null)
results.add(Result(name, mark))
}
println("Class Results")
println("-".repeat(32))
results.sortByDescending { it.mark }
results.forEachIndexed { i, result ->
println("${i+1}. $result")
}
val total = results.sumOf { it.mark }
val average = total.toDouble() / results.size
println("-".repeat(32))
println("Average Mark %.1f".format(average))
}
class Result (
val name: String,
val mark: Int
) {
fun grade(): String = when (mark) {
in 0..24 -> "Not Achieved"
in 25..49 -> "Achieved"
in 50..74 -> "Merit"
in 75..100 -> "Excellence"
else -> "unknown"
}
override fun toString(): String {
var info = name.padEnd(15)
info += mark.toString().padStart(3)
info += " " + grade()
return info
}
}
Program Output
This program shows off some of the neat, concise Kotlin syntax: data collections, classes, forEach, when, String templates, null safety, etc.
Here is an example run for the program:
$ java -classpath kotlin-stdlib.jar MainKt
Name: Jimmy Smith
Mark: 13
Name: Shelly Gnome
Mark: 100
Name: Tane Jones
Mark: 78
Name: Dave Turnip
Mark: 32
Name: Karen Lentil
Mark: ⏎
Mark: ⏎
Mark: 59
Name: Kate Williams
Mark: 85
Name: Tim Gorilla
Mark: 8
Name: ⏎
Class Results
-----------------------------------
1. Shelly Gnome 100 Excellence
2. Kate Williams 85 Excellence
3. Tane Jones 78 Excellence
4. Katen Lentil 59 Merit
5. Dave Turnip 32 Achieved
6. Jimmy Smith 13 Not Achieved
7. Tim Gorilla 8 Not Achieved
-----------------------------------
Average Mark 53.6
$ Process finished with exit code 0