PM-14805: Ensure results cannot be double wrapped from 'asSuccess' (#4283)

This commit is contained in:
David Perez 2024-11-11 14:46:55 -06:00 committed by GitHub
parent c5293715e1
commit 771e719963
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 16 additions and 1 deletions

View file

@ -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]. * 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) Result.success(this)
}
/** /**
* Returns the given [Throwable] as a "failure" [Result]. * Returns the given [Throwable] as a "failure" [Result].

View file

@ -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 @Test
fun `asFailure returns a failure Result with the correct content`() { fun `asFailure returns a failure Result with the correct content`() {
val throwable = IllegalStateException("Test") val throwable = IllegalStateException("Test")