Skip to content

Instantly share code, notes, and snippets.

@alorma
Last active February 8, 2018 16:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alorma/5c442c8b851693d55d76ccad3e8307dc to your computer and use it in GitHub Desktop.
Save alorma/5c442c8b851693d55d76ccad3e8307dc to your computer and use it in GitHub Desktop.
Kotlin calendar DSL
import java.util.*
@DslMarker
annotation class CalendarDsl
@CalendarDsl
class CalendarBuilder(val calendar: Calendar) {
fun dayOfMonth(function: () -> Int) = calendar.apply { set(Calendar.DAY_OF_MONTH, function()) }
fun dayOfMonth(value: Int) = calendar.apply { set(Calendar.DAY_OF_MONTH, value) }
fun month(function: () -> Int) = calendar.apply { set(Calendar.MONTH, function()) }
fun month(value: Int) = calendar.apply { set(Calendar.MONTH, value) }
fun year(function: () -> Int) = calendar.apply { set(Calendar.YEAR, function()) }
fun year(value: Int) = calendar.apply { set(Calendar.YEAR, value) }
fun hourOfDay(function: () -> Int) = calendar.apply { set(Calendar.HOUR_OF_DAY, function()) }
fun hourOfDay(value: Int) = calendar.apply { set(Calendar.HOUR_OF_DAY, value) }
fun minute(function: () -> Int) = calendar.apply { set(Calendar.MINUTE, function()) }
fun minute(value: Int) = calendar.apply { set(Calendar.MINUTE, value) }
fun date(dayOfMonth: Int, month: Int, year: Int) = calendar.apply {
set(Calendar.DAY_OF_MONTH, dayOfMonth)
set(Calendar.MONTH, month)
set(Calendar.YEAR, year)
}
fun time(hourOfDay: Int, minute: Int) = calendar.apply {
set(Calendar.HOUR_OF_DAY, hourOfDay)
set(Calendar.MINUTE, minute)
}
}
@CalendarDsl
fun kalendar(setup: CalendarBuilder.() -> Unit): Calendar = with(CalendarBuilder(Calendar.getInstance())) {
setup()
calendar
}
@CalendarDsl
fun Calendar.dsl(setup: CalendarBuilder.() -> Unit): Calendar = with(CalendarBuilder(this)) {
setup()
calendar
}
private fun generateFakeCalendar() = kalendar {
dayOfMonth { 12 }
month { 3 }
year { 2019 }
hourOfDay { 9 }
minute { 27 }
}
private fun generateFakeCalendar() = kalendar {
dayOfMonth(12)
month(3)
year(2019)
hourOfDay(9)
minute(27)
}
private fun generateFakeCalendar() = kalendar {
date(12, 3, 2019)
time(9, 27)
}
private fun generateFakeCalendar() = Calendar.getInstance().dsl {
dayOfMonth(12)
month(3)
year(2019)
hourOfDay(9)
minute(27)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment