Skip to content

Commit

Permalink
Added nullable version of enum
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Dec 30, 2023
1 parent 7502036 commit c52ba20
Showing 1 changed file with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -15,3 +16,16 @@ inline fun <I, E, reified ENUM : Enum<ENUM>> Parser<I, String, E>.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 <I, E, reified ENUM : Enum<ENUM>> Parser<I, String?, E>.enum(crossinline ifError: (String) -> E): Parser<I, ENUM?, E> {
return flatMap { symbol ->
if (symbol == null) Either.Right(null)
else runCatching { enumValueOf<ENUM>(symbol) }
.fold({ it.right() }, { ifError(symbol).leftNel() })
}
}

0 comments on commit c52ba20

Please sign in to comment.