All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.apollographql.apollo3.api.Optional.kt Maven / Gradle / Ivy

There is a newer version: 4.0.0-beta.7
Show newest version
package com.apollographql.apollo3.api

import com.apollographql.apollo3.api.Optional.Absent
import com.apollographql.apollo3.api.Optional.Present
import com.apollographql.apollo3.exception.MissingValueException
import kotlin.jvm.JvmStatic

/**
 * A sealed class that can either be [Present] or [Absent]
 *
 * It provides a convenient way to distinguish the case when a value is provided explicitly and should be
 * serialized (even if it's null) and the case where it's absent and shouldn't be serialized.
 */
sealed class Optional {
  /**
   * 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(val value: V) : Optional()
  object Absent : Optional()

  companion object {
    @JvmStatic
    fun  absent(): Optional = Absent

    @JvmStatic
    fun  present(value: V): Optional = Present(value)

    @JvmStatic
    fun  presentIfNotNull(value: V?): Optional = if (value == null) Absent else Present(value)
  }
}

/**
 * Returns the value if this [Optional] is [Present] or null else.
 */
fun  Optional.getOrElse(fallback: V): V = (this as? Present)?.value ?: fallback




© 2015 - 2025 Weber Informatics LLC | Privacy Policy