Skip to content

Instantly share code, notes, and snippets.

@ovitrif
Forked from ArneKoeckeritz/gist:f39a8c711473f4ceb8dbea9cc1dd5e5e
Last active October 27, 2023 12:39
Show Gist options
  • Save ovitrif/9877ab8ce19bd3fab98c399e13f768e6 to your computer and use it in GitHub Desktop.
Save ovitrif/9877ab8ce19bd3fab98c399e13f768e6 to your computer and use it in GitHub Desktop.
Test @ komoot
enum class Sport { HIKE, RUN, TOURING_BICYCLE, E_TOURING_BICYCLE }
data class Summary(val sport: Sport, val distance: Int)
fun main() {
val sportStats = listOf(
Summary(Sport.HIKE, 92),
Summary(Sport.RUN, 77),
Summary(Sport.TOURING_BICYCLE, 322),
Summary(Sport.E_TOURING_BICYCLE, 656)
)
// Write kotlin code to print the top sport by distance excluding eBikes.
/**
* Solution Arguments:
* 1. inline = No need to store a variable since we won't use the value again
* 2. predicate inside maxByOrNull = avoid iterating twice over the list
* 3. takeIf = more concise than if/else, because unfortunately, Kotlin has no ternary operator
*/
println(
sportStats
.maxByOrNull { it.distance.takeIf { _ -> it.sport != Sport.E_TOURING_BICYCLE } ?: 0 }
?.sport
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment