You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala遍历List时处理Future[Option[T]]如何过滤None值

解决方案

推荐方案:直接过滤不存在的评论(无需构造空实例)

def getCommentListWithDetail(
      targetId: Long,
      sortOrder: CommentOrderEnum,
      page: Int): Future[Seq[CommentDetailDTO]] = {
    commentModel.getCommentIds(targetId, sortOrder).flatMap { commentStatsBOSeq =>
      Future.traverse(commentStatsBOSeq) { commentStatsBO =>
        getCommentDetail(commentStatsBO.iId).map { commentOpt =>
          // 仅对存在的评论填充回复数,不存在的保留None
          commentOpt.map(_.copy(replyCount = Some(commentStatsBO.replyCount)))
        }
      // flatten会自动过滤所有None,提取存在的评论对象
      }.map(_.flatten)
    }
  }

原代码调用getOrElse(CommentDetailDTO)报错的原因是CommentDetailDTO的必填构造参数id/author/detail没有设置默认值,无法直接生成空实例。不需要保留占位记录的场景下,直接保留Option类型结果,批量查询完成后调用flatten即可自动过滤无效的None记录,最终返回的序列仅包含真实存在的评论数据。


可选方案:构造空评论占位实例

如果业务需要保留无效评论的占位,可给CommentDetailDTO的必填参数设置默认值:

case class CommentDetailDTO(
    id: Long = 0L,
    author: JsObject = Json.obj(),
    detail: CommentDetail = CommentDetail(), // 同步给CommentDetail设置合理默认值即可
    replyCount: Option[Int] = None
)

配置完成后原有的getOrElse(CommentDetailDTO)代码即可正常编译运行。

内容的提问来源于stack exchange,提问作者BugSource

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:15:02