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

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

The newest version!
package com.apollographql.apollo.api

import com.apollographql.apollo.annotations.ApolloExperimental
import com.apollographql.apollo.api.Optional.Absent
import com.apollographql.apollo.api.Optional.Present
import com.apollographql.apollo.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(): Absent = Absent

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

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

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

@ApolloExperimental
fun  Optional.map(mapper: (V) -> R): Optional {
  return when(this) {
    is Absent -> Absent
    is Present -> Optional.present(mapper(value))
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy