Joram Visser
08/31/2019, 8:55 PMimport arrow.Kind
import arrow.core.Either
import arrow.core.Left
import arrow.core.Right
import arrow.effects.typeclasses.MonadDefer
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Date
class DateParseError(val message: String)
private const val DATE_FORMAT = "yyyyMMdd"
private const val DEFAULT_DATE_PARSE_ERROR_MESSAGE = "An exception was thrown while parsing the date string."
private val dateFormat: DateFormat = SimpleDateFormat(DATE_FORMAT)
fun <F> MonadDefer<F>.parse(date: String): Kind<F, Either<DateParseError, Date>> =
catch {
Right(dateFormat.parse(date))
}.handleError {
Left(DateParseError(it.message ?: DEFAULT_DATE_PARSE_ERROR_MESSAGE))
}