【问题标题】:ArrowKt Try alternative for eager executionArrowKt 尝试急切执行的替代方案
【发布时间】:2020-01-20 14:03:57
【问题描述】:

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

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

【问题讨论】:

    标签: kotlin functional-programming arrow-kt


    【解决方案1】:

    现在有一种更简单的方法

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

    【讨论】:

      【解决方案2】:

      在 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() }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-29
        • 1970-01-01
        • 1970-01-01
        • 2017-06-17
        • 2019-06-23
        • 2011-05-28
        相关资源
        最近更新 更多