/nullobjectpattern-good-usage.kt Secret
Created
April 26, 2020 10:27
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class Workout(val duration: Duration) | |
class Walking(duration: Duration) : Workout(duration) | |
class Swimming(duration: Duration) : Workout(duration) | |
class Running(duration: Duration) : Workout(duration) | |
fun workoutService(date: LocalDate): Workout? { | |
val workouts = mapOf( | |
LocalDate.of(2020, 4, 25) to Walking(Duration.ofHours(2)), | |
LocalDate.of(2020, 4, 23) to Swimming(Duration.ofHours(1)), | |
LocalDate.of(2020, 4, 22) to Running(Duration.ofMinutes(30)) | |
) | |
return workouts[date] | |
} | |
fun main() { | |
val days = listOf( | |
LocalDate.of(2020, 4, 22), LocalDate.of(2020, 4, 23), LocalDate.of(2020, 4, 24), LocalDate.of(2020, 4, 25) | |
) | |
var sum: Long = 0 | |
for(day in days) { | |
val workout = workoutService(day) | |
if (workout == null) { | |
continue | |
} | |
sum = sum + workout.duration.toMillis() | |
} | |
println("Total duration: ${Duration.ofMillis(sum)}") // Total duration: PT3H30M | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment