kotlin - ArrowKt Try渴望执行的替代方法

标签 kotlin functional-programming arrow-kt

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/

相关文章:

mongodb - ReactiveMongoRepository/MongoRepository不返回_id字段

haskell - 如何实现纯函数式标准二进制堆(ocaml 或 haskell)?

kotlin - 任何人都可以激发为什么 Arrow (Kotlin) 选择弃用更高级的类型?

android - 即使在postValue()Kotlin之后,MutableLiveData ArrayList也为空

java - 运行时异常 : Unable to instantiate activity ComponentInfo . .. ClassNotFoundException

Android studio 注销 : clear saved preferences kotlin

math - 函数式编程中的对偶方法

r data.table 函数式编程/元编程/语言计算

kotlin - 是否有任何理由使用 suspend fun fn(...) : Either<Throwable, A> 而不是 suspend fun fn(...) : A?

Kotlin 等效于联合类型上的某些 F# 代码匹配