ArrowKt has deprecated Try since it promotes eager execution of effects and it recommends to use suspend constructors. But how should I handle following case where I do want eager execution on purpose without using traditional try-catch.
fun getMainAccount(accounts: List<String>): Either<Exception, String> {
return Try {
accounts.single()
}.toEither().mapLeft {
InvalidAccountError()
}
}
There is no need for any special construct beside try/catch
in Kotlin, since it's also already an expression. For that reason it was removed from Arrow, you can simply write:
fun getMainAccount(accounts: List<String>): Either<Exception, String> =
try {
Right(accounts.single())
} catch(e: Exception) {
Left(InvalidAccountError())
}
Or you can also easily write a utility function for it yourself.
fun <A> Try(f: () -> A, fe: ): Either<Exception, A> =
try {
Right(f())
} catch(e: Exception) {
Left(e)
}
fun getMainAccount(accounts: List<String>): Either<Exception, String> =
Try { accounts.single() }.mapLeft { InvalidAccountError() }