Skip to content

Introduction

MerlinTHS edited this page Feb 17, 2023 · 2 revisions

...

Comparison

Using standard Kotlin

import java.util.Optional

fun main() {
    val name = parseName("Hello Kotlin!")

    name.ifPresentOrElse(
        action = { name ->
            println("Bye $name!")
        },
        emptyAction = {
            println("Unable to parse a name!")
        }
    )
}

fun parseName(greeting: String): Optional<String> {
    if (greeting.isBlank() or !greeting.endsWith("!")) {
        return Optional.empty()
    }

    val name = "Hello\\s([^!]*)!"
        .toRegex()
        .find(greeting)


    return Optional.ofNullable(
        name?.groupValues?.get(1)
    )
}

Using Kava

import io.mths.kava.validator.extensions.*
import io.mths.kava.result.onFailure

fun main() {
    validate {
        val name by parseName("Hello Kotlin!")

        println("Bye $name!")
    } onFailure {
        println("Unable to parse a name!")
    }
}

fun parseName(greeting: String) = optional {
    + greeting { isNotBlank() and endsWith("!") }
    
    val name by "Hello\\s([^!]*)!"
        .toRegex()
        .find(greeting)

    name.groupValues[1]
}