ArrowKt 尝试替代急切执行

Ali*_*lan 1 functional-programming kotlin arrow-kt

ArrowKt 已弃用Try,因为它会促进效果的急切执行,并且建议使用挂起构造函数。但是,如果我确实希望在不使用传统的try-catch 的情况下有意执行,我应该如何处理以下情况。

 fun getMainAccount(accounts: List<String>): Either<Exception, String> {  
   return Try {
     accounts.single()
   }.toEither().mapLeft {
     InvalidAccountError()
   }
 }
Run Code Online (Sandbox Code Playgroud)

nom*_*Rev 5

除了 Kotlin之外,不需要任何特殊的构造try/catch,因为它也已经是一个表达式。因此它被从 Arrow 中删除,你可以简单地写:

fun getMainAccount(accounts: List<String>): Either<Exception, String> =  
   try {
     Right(accounts.single())
   } catch(e: Exception) {
     Left(InvalidAccountError())
   }
Run Code Online (Sandbox Code Playgroud)

或者您也可以轻松地自己为其编写一个实用函数。

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() }
Run Code Online (Sandbox Code Playgroud)


Ser*_*del 5

现在有一个更简单的方法

fun getMainAccount(accounts: List<String>): Either<Exception, String> = 
    Either.catch {accounts.single()}

Run Code Online (Sandbox Code Playgroud)