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

Fix Optional<V>.getOrThrow() when V is nullable #5192

Merged
merged 2 commits into from
Aug 17, 2023
Merged
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 @@ -12,8 +12,20 @@ import kotlin.jvm.JvmStatic
* serialized (even if it's null) and the case where it's absent and shouldn't be serialized.
*/
sealed class Optional<out V> {
fun getOrNull() = (this as? Present)?.value
fun getOrThrow() = getOrNull() ?: throw MissingValueException()
/**
* Returns the value if this [Optional] is [Present] or null else.
*/
fun getOrNull(): V? = (this as? Present)?.value

/**
* Returns the value if this [Optional] is [Present] or throws [MissingValueException] else.
*/
fun getOrThrow(): V {
if (this is Present) {
return value
}
throw MissingValueException()
}

data class Present<V>(val value: V) : Optional<V>()
object Absent : Optional<Nothing>()
Expand Down
33 changes: 30 additions & 3 deletions libraries/apollo-api/src/commonTest/kotlin/test/OptionalTest.kt
Original file line number Diff line number Diff line change
@@ -1,20 +1,47 @@
package test

import com.apollographql.apollo3.api.Optional
import com.apollographql.apollo3.exception.MissingValueException
import kotlin.test.Test
import kotlin.test.assertFails
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNull
import kotlin.test.fail

class OptionalTest {
@Test
fun presentTest() {
fun present() {
assertIs<Optional.Present<*>>(Optional.present("some value"))
assertIs<Optional.Present<*>>(Optional.present(null))
}

@Test
fun presentIfNotNullTest() {
fun presentIfNotNull() {
assertIs<Optional.Present<*>>(Optional.presentIfNotNull("some value"))
assertIs<Optional.Absent>(Optional.presentIfNotNull(null))
}

@Test
fun getOrThrowNull() {
val optional = Optional.present<String?>(null)
val value = optional.getOrThrow()
assertNull(value)
}

@Test
fun getOrThrowPresent() {
val optional = Optional.present<String?>("hello")
val value = optional.getOrThrow()
assertEquals("hello", value)
}

@Test
fun getOrThrowAbsent() {
val optional = Optional.absent<String?>()
try {
val value = optional.getOrThrow()
fail("An exception was expected but got '$value' instead")
} catch (_: MissingValueException) {
}
}
}
Loading