Watch video

Video

Latest snapshot Publish artifacts Publish documentation Kotlin version badge License

Functional companion to Kotlin’s Compiler & IDE

Λrrow Meta is a meta-programming library designed to build compiler plugins for Kotlin.

The Λrrow org bundles independent plugins built with Λrrow meta.

Refined Types

A refined type is any regular type constrained by predicates expected to hold in all possible values of the type’s constructor.

The refined-types plugin monitors all calls to Refined type constructors, ensuring arguments provided are verifiable in the range of the declared predicates constraining the type.

Consider the use case of modeling a port number. Instead of using Int to describe a port, we will create our own Port type and enable the refined-types capabilities by making the Port companion extend the Refined class.

import arrow.refinement.Refined
import arrow.refinement.ensure

@JvmInline
value class Port /* private constructor */ (val value: Int) {
  companion object : Refined<Int, Port>(::Port, {
    ensure((it in 0..65535) to "$it should be in the closed range of 0..65535 to be a valid port number")
  })
}

When attempting to instantiate a Port with invalid values as constants, the plugin fails at compile-time and forces us to correct the input preventing a potential runtime exception.

Port(70000)
// error: "$it should be in the closed range of 0..65535 to be a valid port number"

For cases where the input values are dynamic and not evaluable at compile-time, the plugin advises us to use a safe API based on nullable types.

fun f(n: Int) {
  Port(n)
}
// error: Prefer a safe alternative such as Port.orNull(n) or for explicit use of exceptions `Port.require(n)`

The refined type plugin includes a runtime API that can be used without the plugin to validate types:

Port.orNull(5555)
// Port(value=5555)
Port.orNull(70000)
try { Port.require(70000) } catch (e: IllegalArgumentException) { e.message }
// 70000 should be in the closed range of 0..65535 to be a valid port number

Learn more about Refined Types

Do you like Arrow?

Arrow Org
<