Last active
April 26, 2020 10:39
-
-
Save le0nidas/7e2d974cfbfe648a5f393eec3bf4dfd2 to your computer and use it in GitHub Desktop.
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) | |
// null object: | |
object NoWorkout : Workout(Duration.ZERO) | |
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] ?: NoWorkout // usage of null object | |
} | |
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) | |
sum = sum + workout!!.duration.toMillis() // yes, we are that!! sure | |
} | |
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