Kotlin
Date helpers
Add LocalDate processing functions.
LocalDate extension
This lesson adds the isWeekend extension to LocalDate. It returns whether the date is on a weekend.
Example: fun LocalDate.isWeekend(): Boolean { val day = dayOfWeek.value; return day == 6 || day == 7 }. Using LocalDate requires import java.time.LocalDate. dayOfWeek.value returns 1 for Monday and 7 for Sunday. Saturday 6 and Sunday 7 are the weekend. LocalDate.of(2024, 1, 6).isWeekend() returns true.
dayOfWeek and the weekend
The dayOfWeek property of LocalDate gives the day of the week. With .value you get its number: Monday 1, Sunday 7.
Example: LocalDate.of(2024, 1, 6).dayOfWeek.value returns 6 because January 6, 2024 is a Saturday. For a weekend check use day == 6 || day == 7. This pattern collects the weekend logic in one extension function instead of rewriting it on every call.
Exercise Add the LocalDate.isWeekend extension
Alongside the existing Helpers object, String.titleCase and Int.squared extensions, add a LocalDate.isWeekend() extension. First put import java.time.LocalDate at the top of the file. The extension body runs val day = dayOfWeek.value; return day == 6 || day == 7. In main print Helpers.greet("Alex"), "hello world".titleCase(), 5.squared() and LocalDate.of(2024, 1, 6).isWeekend() with println.
Show example solution
import java.time.LocalDate
object Helpers {
fun greet(name: String): String {
return "Hello, $name!"
}
}
fun String.titleCase(): String {
return split(" ").joinToString(" ") { word ->
word.lowercase().replaceFirstChar { it.uppercase() }
}
}
fun Int.squared(): Int {
return this * this
}
fun LocalDate.isWeekend(): Boolean {
val day = dayOfWeek.value
return day == 6 || day == 7
}
fun main() {
println(Helpers.greet("Alex"))
println("hello world".titleCase())
println(5.squared())
println(LocalDate.of(2024, 1, 6).isWeekend())
}
Test yourself
-
Complete the LocalDate extension definition
fun ____.isWeekend(): Boolean {
val day = dayOfWeek.value
return day == 6 || day == 7
}
Show answer
fun LocalDate.isWeekend(): Boolean {
val day = dayOfWeek.value
return day == 6 || day == 7
}
-
Match the LocalDate extension parts
- import java.time.LocalDate
- Import
- fun LocalDate.isWeekend()
- Receiver and method
- dayOfWeek.value
- Day number
- day == 6 || day == 7
- Weekend condition
-
What does the <code>fun LocalDate.isWeekend(): Boolean</code> extension return?
- A String
- An Int
- A Boolean
- A LocalDate
Show answer
A Boolean — isWeekend returns a Boolean; whether it is the weekend.
Next lesson: Putting it together