Scala:如何使用map而不是isEmpty和if

时间:2017-09-06 18:46:59

标签: scala

新手斯卡拉问题。 我有以下代码:

val mathsResult = mathsFunction
val comments = Seq(a, b, c).flatten 
CalculationResult(mathsResult, if (comments.isEmpty) None else Some(comments.mkString("\n")))

有人说我可以使用map作为最后一行,但我尝试了几种方法而无法使其发挥作用。 CalculationResult需要Option[String]

2 个答案:

答案 0 :(得分:3)

你可以说

Some(comments).filterNot(_.isEmpty).map(_.mkString("\n"));
// Some(comments)        -- Some(comments)
// filterNot(_.isEmpty)  -- if(comments.isEmpty) None else Some(comments)
// map(_.mkString("\n")) -- if(comments.isEmpty) None else Some(comments.mkString("\n"))
// except comments is only evaluated once

您也可以进行折叠:

comments.foldLeft(None: Option[String]) {
  case (Some(acc), elem) => Some(s"$acc\n$elem");
  case (_, elem) => Some(elem)
}

但它并不像上面那么简洁。

答案 1 :(得分:1)

您可以将mkString功能合并到reduceOption部分函数参数中。

val comments: Seq[String] = Seq()  // no comments
comments.reduceOption(_+"\n"+_)    // mkString
// res0: Option[String] = None

val comments: Seq[String] = Seq("a", "b", "c")  // 3 comments
comments.reduceOption(_+"\n"+_)                 // mkString
// res1: Option[String] = Some(a
// b
// c)