Skip to content

Commit

Permalink
Use contracts for isPresent (#950)
Browse files Browse the repository at this point in the history
  • Loading branch information
DRSchlaubi authored Aug 21, 2023
1 parent 8a6c376 commit a7d1c03
Showing 1 changed file with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.jvm.JvmInline

@Serializable(with = OmissableSerializer::class)
Expand Down Expand Up @@ -70,9 +72,21 @@ class OmissableSerializer<T>(private val childSerializer: KSerializer<T>) : KSer
}
}

fun <T : Any> Omissible<T>.isPresent() = this is Omissible.Present
@OptIn(ExperimentalContracts::class)
fun <T : Any> Omissible<T>.isPresent(): Boolean {
contract {
returns(true) implies (this@isPresent is Omissible.Present<T>)
}
return this is Omissible.Present
}

fun <T : Any> Omissible<T>.isOmitted() = this is Omissible.Omitted
@OptIn(ExperimentalContracts::class)
fun <T : Any> Omissible<T>.isOmitted(): Boolean {
contract {
returns(true) implies (this@isOmitted is Omissible.Omitted<T>)
}
return this is Omissible.Omitted
}

fun <T : Any?> Omissible<T>.takeIfPresent(predicate: (T) -> Boolean = { true }) =
if (this is Omissible.Present) value.takeIf(predicate) else null
Expand Down

0 comments on commit a7d1c03

Please sign in to comment.