dev.forkhandles.values.result.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of values4k Show documentation
Show all versions of values4k Show documentation
ForkHandles Value-types library
The newest version!
package dev.forkhandles.values
/**
* Return a Result Success/Failure based on validation.
*/
fun , PRIMITIVE : Any> ValueFactory.parseResult(value: String) =
Result.runCatching { validate(parseFn(value)) }
fun , PRIMITIVE : Any> ValueFactory.ofListResult(values: List) =
values.toResult(::ofResult)
fun , PRIMITIVE : Any> ValueFactory.ofListResult(vararg values: PRIMITIVE) =
ofListResult(values.toList())
fun , PRIMITIVE : Any> ValueFactory.parseListResult(values: List) =
values.toResult(::parseResult)
fun , PRIMITIVE : Any> ValueFactory.parseListResult(vararg values: String) =
parseListResult(values.toList())
fun , PRIMITIVE : Any> ValueFactory.ofResult(value: PRIMITIVE) =
Result.runCatching { validate(value) }
private fun , PRIMITIVE : Any> List.toResult(
fn: (IN) -> Result
) = when {
isEmpty() -> Result.success(emptyList())
else ->
drop(1)
.fold(fn(first()).map(::listOf)) { acc, next ->
when {
acc.isSuccess -> fn(next).map { acc.getOrThrow() + it }
else -> acc
}
}
}