ArrowKt 尝试替代急切执行
ArrowKt Try alternative for eager execution
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() }
现在有更简单的方法
fun getMainAccount(accounts: List<String>): Either<Exception, String> =
Either.catch {accounts.single()}
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() }
现在有更简单的方法
fun getMainAccount(accounts: List<String>): Either<Exception, String> =
Either.catch {accounts.single()}