Skip to content

Custom Types

MerlinTHS edited this page Feb 16, 2023 · 1 revision

Assume we want to add a new type Result for modelling optional behavior.

sealed interface Result<Type> {
    class Failure<Type> : Result<Type>
    
    data class Success<Type>(
        val value: Type
    ) : Result<Type>
}

Implement the Validator interface and annotate it with @GenerateExtensions.

The compilation will fail, if you annotate classes that don't implement this interface!

import io.mths.kava.*

@GenerateExtensions("result")
class ResultValidator<Type> : Validator<Type, Result<Type>> {
    override val invalid =
        Result.Failure<Type>()

    override fun valid(value: Type) =
        Result.Success(value)

    override fun ValidationScope<*>.validate(
        wrapper: Result<Type>
    ) = when (wrapper) {
        is Result.Success -> wrapper.value
        else -> fail()
    }
}

After building the project, you can use the generated result function.

fun mayGreet(name: String) = result {
    + name { isNotBlank() }
    
    "Hello $name!"
}