Skip to content

Instantly share code, notes, and snippets.

@Cotel
Last active November 25, 2018 10:35
Show Gist options
  • Save Cotel/7ceccc7458287df380b962d9612c1c5c to your computer and use it in GitHub Desktop.
Save Cotel/7ceccc7458287df380b962d9612c1c5c to your computer and use it in GitHub Desktop.
How to make refined types in Kotlin with Arrow (https://arrow-kt.io/)
import arrow.core.Option
class NonZeroInt private constructor(val value: Int) {
companion object {
operator fun invoke(x: Int): Option<NonZeroInt> =
if (x == 0) Option.empty() else Option.just(NonZeroInt(x))
fun get(x: NonZeroInt): Int = x.value
}
}
fun safeDivide(x: Int, y: NonZeroInt): Int = x / y.value
val partialOperation = { divisor: NonZeroInt -> safeDivide(30,divisor) }
val someResult = NonZeroInt(12).map(partialOperation)
val emptyResult = NonZeroInt(0).map(partialOperation)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment