M S
M S

Reputation: 19

Scala: How to use map instead of isEmpty and if

Newbie Scala question. I have the following code:

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

Someone said I could use map for the last line, but I've tried a few ways and couldn't get it to work. CalculationResult expects an Option[String].

Upvotes: 2

Views: 282

Answers (2)

jwvh
jwvh

Reputation: 51271

You can incorporate the mkString functionality into the reduceOption partial function argument.

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)

Upvotes: 1

HTNW
HTNW

Reputation: 29148

You can say

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

You can also do a fold:

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

but it's not as concise as the above.

Upvotes: 3

Related Questions