I'm learning functional programming in Kotlin using arrow library and I come across below strange behaviour of fold function of Either type (at least for me).
import arrow.core.*
import arrow.syntax.function.pipe
object UserService {
fun findAge(user: String): Either<String, Option<Int>> {
return Either.Right(Some(1))
}
}
fun main(args: Array<String>) {
val anakinAge: Either<String, Option<Int>> = UserService.findAge("Anakin")
anakinAge.fold({itLeft -> itLeft.toUpperCase()},{itRight -> itRight.fold({ 1 }, {it})}) pipe ::println
}
as per the arrow fold function syntax is
inline fun <C> fold(ifLeft: (A) -> C, ifRight: (B) -> C): C
if the value is Left it executes ifLeft function and returns type C if it's right it executes ifRight and returns a value with the same type C, but in my above code snippet am returning String if the value is Left and Int if the value is Right. How does it accept this syntax?
In here, fold
finds the first common parent of the types String
and Int
, which is Any
. In Kotlin, unlike Java, there are no basic types, it's all objects.
So, if you use the result to any function that doesn't take Any
, it fails.
fun check(s: String): String = s
van a = anakinAge.fold({itLeft -> itLeft.toUpperCase()},{itRight -> itRight.fold({ 1 }, {it})})
check(a)
yields Type mismatch: inferred type is Any but String was expected
.