Making a Scala version of this Java method
1 answer
Instead of navigating the tracks to find the value you want lanes find (_.number == 42)
.
Express guards as filters and defaults as getOrElse
.
Example:
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 to small functions for getting x find goodNumber
, etc.
More reviews:
Folding is commendable, but usually you want to use max
or maxBy
if that's what you do.
spots maxBy (_.name.toInt)
You can express your missing condition as part of a fold, but it's easier to just scan the list again:
if (spots exists (!_.model.equalsIgnoreCase(vehicle.model))) fail
You can optimize later if needed.
+2
source to share