Skip to content

Vanilla

MerlinTHS edited this page Feb 17, 2023 · 2 revisions

Vanilla is the first compiler-plugin assisted flavor of Kava.

Functions annoated with @Kava will be transformed by the plugin, to run inside a ValidationScope. That's why you can use all the Kava stuff inside, without wrapping it into a scope builder like optional.

@Kava
fun parseName(greeting: Name): String {
  + greeting { isNotBlank() and ensWith("!") }

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

  return name.groupValues[1]
}

When calling it from inside a ValidationScope validation is done automatically. There's no need to use Validation by Delegation or the Snowflake Extension.

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

  println("Bye $name!")
}

To call it from outside a ValidationScope, wrap it into the scope builder of the type you're interested in. For example a java.util.Optional.

fun main() {
  val mayName = optional {
    parseName("Hello Vanilla!")
  }

  mayName.ifPresent { name ->
    println("Bye $name!")
  }
}

Or as a nullable type.

fun main() {
  val mayName = nullable {
    parseName("Hello Vanilla!")
  }

  if (mayName != null) {
    println("Bye $mayName!")
  }
}

So the call-site decides which optional type should be used to represent the value!

Clone this wiki locally