加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何展平试试[选项[T]]

发布时间:2020-12-16 18:58:24 所属栏目:安全 来源:网络整理
导读:我想将Try [Option [T]]压平成Try [T] 这是我的代码 def flattenTry[T](t: Try[Option[T]]) : Try[T] = { t match { case f : Failure[T] = f.asInstanceOf[Failure[T]] case Success(e) = e match { case None = Failure[T](new Exception("Parsing error")
我想将Try [Option [T]]压平成Try [T]

这是我的代码

def flattenTry[T](t: Try[Option[T]]) : Try[T] = {
  t match {
    case f : Failure[T] => f.asInstanceOf[Failure[T]]
    case Success(e) => 
      e match {
        case None => Failure[T](new Exception("Parsing error"))
        case Some(s) => Success(s)
      }
  }
}

有没有更好的办法 ?

解决方法

你可以试试这样的东西,有点整洁:

val t = Try(Some(1))
val tt = t.flatMap{
  case Some(i) => Success(i) 
  case None => Failure(new Exception("parsing error"))
}

更一般地说,这将是:

def flattenTry[T](t: Try[Option[T]]) : Try[T] = {
  t.flatMap{
    case Some(s) => Success(s) 
    case None => Failure(new Exception("parsing error"))
  }    
}

诀窍是将Option转换为Try以使用flatmap.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读