Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toErrorIfNull to return Result with non-null value. #86

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,18 @@ public inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, trans
*
* @see [toErrorIf]
*/
public inline fun <V, E> Result<V, E>.toErrorIfNull(error: () -> E): Result<V, E> {
public inline fun <V, E> Result<V?, E>.toErrorIfNull(error: () -> E): Result<V, E> {
contract {
callsInPlace(error, InvocationKind.AT_MOST_ONCE)
}

return toErrorIf(
{ it == null },
{ error() }
)
).map {
@Suppress("UNCHECKED_CAST")
it as V
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ class MapTest {

@Test
fun returnsTransformedErrorIfNull() {
val result = Ok(null).toErrorIfNull { "a" }
val result: Result<Nothing, String> = Ok(null).toErrorIfNull { "a" }
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would not have compiled before because the return type of toErrorIfNull was Result<Nothing?, String> which should not be possible.


result as Err

Expand Down