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

commonMain.dev.mokkery.matcher.capture.SlotCapture.kt Maven / Gradle / Ivy

Go to download

Mokkery is a mocking library for Kotlin Multiplatform, easy to use, boilerplate-free and compiler plugin driven.

The newest version!
package dev.mokkery.matcher.capture

import dev.drewhamilton.poko.Poko
import dev.mokkery.internal.AbsentValueInSlotException
import kotlin.reflect.KProperty

/**
 * [Capture] that stores only the last value.
 */
public interface SlotCapture : ContainerCapture {

    /**
     * Contains only latest value.
     */
    override val values: List

    /**
     * If no captured values it returns [Value.Absent].
     * Otherwise, it returns the last captured value wrapped with [Value.Present]
     */
    public val value: Value

    public sealed interface Value {

        /**
         * Represents last captured value.
         */
        @Poko
        public class Present(public val value: T): Value {

            override fun toString(): String = "Present(value=$value)"
        }

        /**
         * Represents absence of captured value.
         */
        public data object Absent: Value
    }
}

/**
 * Returns true if [SlotCapture.value] is [SlotCapture.Value.Present].
 */
public val  SlotCapture.isPresent: Boolean get() = value is SlotCapture.Value.Present

/**
 * Returns true if [SlotCapture.value] is [SlotCapture.Value.Absent].
 */
public val  SlotCapture.isAbsent: Boolean get() = value is SlotCapture.Value.Absent

/**
 * Returns unwrapped [SlotCapture.value] if it is [SlotCapture.Value.Present]. Otherwise, it returns null.
 */
public fun  SlotCapture.getIfPresent(): T? = when (val value = value) {
    is SlotCapture.Value.Present -> value.value
    SlotCapture.Value.Absent -> null
}

/**
 * Returns unwrapped [SlotCapture.value] if it is [SlotCapture.Value.Present]. Otherwise, it fails.
 */
public fun  SlotCapture.get(): T = when (val value = value) {
    is SlotCapture.Value.Present -> value.value
    SlotCapture.Value.Absent -> throw AbsentValueInSlotException()
}

/**
 * Just like [getIfPresent], but as a [getValue] operator.
 */
public operator fun  SlotCapture.getValue(thisRef: Any?, property: KProperty<*>): T? = getIfPresent()





© 2015 - 2024 Weber Informatics LLC | Privacy Policy