commonMain.schemas.EnumSchema.kt Maven / Gradle / Ivy
@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)
}
}