Skip to content

Instantly share code, notes, and snippets.

@le0nidas
Last active April 26, 2020 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save le0nidas/7e2d974cfbfe648a5f393eec3bf4dfd2 to your computer and use it in GitHub Desktop.
Save le0nidas/7e2d974cfbfe648a5f393eec3bf4dfd2 to your computer and use it in GitHub Desktop.
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