Last active
November 25, 2018 10:35
-
-
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/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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