ArrowKt已弃用Try,因为它促进了效果的急切执行,并且建议使用暂停构造函数。
但是,如果我确实希望在不使用传统try-catch的情况下急切执行,那么我该如何处理以下情况?
fun getMainAccount(accounts: List<String>): Either<Exception, String> {
return Try {
accounts.single()
}.toEither().mapLeft {
InvalidAccountError()
}
}
最佳答案
在Kotlin中,除了try/catch
之外,不需要任何特殊的构造,因为它已经是一个表达式。因此,可以将其从Arrow中删除,您只需编写以下内容:
fun getMainAccount(accounts: List<String>): Either<Exception, String> =
try {
Right(accounts.single())
} catch(e: Exception) {
Left(InvalidAccountError())
}
或者,您也可以自己轻松地编写一个实用程序函数。
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() }
关于kotlin - ArrowKt Try渴望执行的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59824918/