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

commonMain.schemas.EnumSchema.kt Maven / Gradle / Ivy

There is a newer version: 0.23.0
Show newest version
@file:OptIn(ExperimentalStdlibApi::class)

package io.kform.schemas

import io.kform.TypeInfo
import io.kform.Validation
import io.kform.schemas.util.commonRestrictions
import kotlin.enums.enumEntries
import kotlin.reflect.KClass
import kotlin.reflect.KType

/**
 * Implementation of a schema representing enum values of type [T]. Use the [EnumSchema] constructor
 * function to create an instance of this class.
 *
 * @property kClass `KClass` of the enum represented by this schema.
 */
public open class EnumSchema>
@PublishedApi
internal constructor(
    public val kClass: KClass,
    validations: Iterable> = emptyList(),
    override val initialValue: T
) : AbstractSimpleSchema(validations) {
    override val typeInfo: TypeInfo =
        TypeInfo(kClass, restrictions = commonRestrictions(validations))

    override fun assignableTo(type: KType): Boolean =
        (type.classifier as? KClass<*>)?.isInstance(initialValue) == true

    public companion object {
        // Since reified types in classes are not supported, we use a reified invoke function to
        // automatically provide the enum's `::class` and initial value.
        /** Function that returns a schema representing enum values of type [T]. */
        public inline operator fun > invoke(
            validations: Iterable> = emptyList(),
            initialValue: T = enumEntries().first()
        ): EnumSchema = EnumSchema(T::class, validations, initialValue)

        public inline operator fun > invoke(
            vararg validations: Validation,
            initialValue: T = enumEntries().first()
        ): EnumSchema = EnumSchema(validations.toList(), initialValue)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy