diff --git a/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/enums/enums.kt b/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/enums/enums.kt index fb89104..c7d7235 100644 --- a/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/enums/enums.kt +++ b/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/enums/enums.kt @@ -1,5 +1,6 @@ package com.sksamuel.tribune.core.enums +import arrow.core.Either import arrow.core.leftNel import arrow.core.right import com.sksamuel.tribune.core.Parser @@ -15,3 +16,16 @@ inline fun > Parser.enum(crossinli .fold({ it.right() }, { ifError(symbol).leftNel() }) } } + +/** + * Wraps a [Parser] that produces nullable Strings to one that produces nullable enums. + * If the String is not a valid enum value, then an error is produced using [ifError]. + * If the String is null, then null is produced. + */ +inline fun > Parser.enum(crossinline ifError: (String) -> E): Parser { + return flatMap { symbol -> + if (symbol == null) Either.Right(null) + else runCatching { enumValueOf(symbol) } + .fold({ it.right() }, { ifError(symbol).leftNel() }) + } +}