Making Scala version of this Java method functiona

2019-09-02 14:32发布

问题:

Trying to port following Java method to Scala. Ending up with a lot of nested Map and ugly return statement from "foreach". converted method looks ugly just like its OO counterpart in Java.

回答1:

Instead of looping through lanes to locate a value, you want to lanes find (_.number == 42).

Express the guards as filters and default values as getOrElse.

Sample:

scala> case class Lane(number: Int)
defined class Lane

scala> val lanes: Seq[Lane] = Nil
lanes: Seq[Lane] = List()

scala> Option(lanes) filter (_.nonEmpty) flatMap (_.find(_.number == 42))
res0: Option[Lane] = None

scala> Option(lanes) filter (_.nonEmpty) flatMap (_.find(_.number == 42)) map (_.number) getOrElse -1
res1: Int = -1

or

scala> for (x <- Option(lanes); y <- x.find(_.number == 42)) yield y.number
res3: Option[Int] = None

Then refactor predicates out to little functions to get x find goodNumber and so on.

More feedback:

Folding is laudable, but usually you want to use max or maxBy if that's what you're doing.

spots maxBy (_.name.toInt)

You could express your missing condition as part of a fold, but it's easier just to scan the list again:

if (spots exists (!_.model.equalsIgnoreCase(vehicle.model))) fail

You can optimize later if necessary.



标签: scala