Skip to content

Commit

Permalink
PM-14805: Ensure results cannot be double wrapped from 'asSuccess' (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
david-livefront authored Nov 11, 2024
1 parent c529371 commit 771e719
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,16 @@ inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> =

/**
* Returns the given receiver of type [T] as a "success" [Result].
*
* Note that this will never double wrap the `Result` and we return the original value if [T] is
* already an instance of `Result`
*/
fun <T> T.asSuccess(): Result<T> =
fun <T> T.asSuccess(): Result<T> = if (this is Result<*>) {
@Suppress("UNCHECKED_CAST")
this as Result<T>
} else {
Result.success(this)
}

/**
* Returns the given [Throwable] as a "failure" [Result].
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ class ResultTest {
)
}

@Test
fun `asSuccess returns a success Result with the correct content that is not double-wrapped`() {
assertEquals(
Result.success("Test"),
"Test".asSuccess().asSuccess(),
)
}

@Test
fun `asFailure returns a failure Result with the correct content`() {
val throwable = IllegalStateException("Test")
Expand Down

0 comments on commit 771e719

Please sign in to comment.