Search code examples
scalaspecs2

Converting a foreach into contains forall matcher


I have the following expression in a spec, with the intention of ensuring that each element has a value distanceToEnd that is very close to the sum of the distanceFromPrevious values of the elements following it.

foo.tails.foreach {
  case h +: t => h.distanceToEnd.miles must
    beCloseTo(t.map(_.distanceFromPrevious.miles).sum, 10e-10)
  case _ => ok
}

Ideally, this should be in the form foo.tails must contain { ... }.forall, but I have trouble understanding how to create the necessary ValueCheck parameter for contains. How would I convert this particular example?


Solution

  • Unfortunately type inference doesn't work with partial functions so you need to match explicitly:

     foo.tails must contain { ts: List[Foo] =>
       ts match {
         case h +: t => h.distanceToEnd.miles must
           beCloseTo(t.map(_.distanceFromPrevious.miles).sum, 10e-10)
         case _ => ok
       }
    }.forall