The code explains itself.
val s = Seq(1,1,1)
val res: Seq[Int] = s.map(...)
.check(count how many 1s, if > 2 throw Exception)
.map(...)
I am searching the simple solution to this check
function .
map
and closure
to count and throw, but I want pure function.filter
and size
or reduce
, but it return a value and not resumable with following maps.How do I make a pure and stateful checking-pipe to the pipeline ?
One solution is to pattern match, so check would become:
> Seq(1, 1) match {
case ls if (ls.count(_ == 1) <= 2) => ls
case _ => throw new Exception("oh no!")
}
List(1, 1): Seq[Int]
> Seq(1, 1, 1) match {
case ls if (ls.count(_ == 1) <= 2) => ls
case _ => throw new Exception("oh no!")
}
java.lang.Exception: oh no!
$.<init>(Main.scala:177)
$.<clinit>(Main.scala:-1)
It may be preferable to return an Option type (instead of throwing):
> Seq(1, 1, 1) match {
case ss if (ss.count(_ == 1) <= 2) => Option(ss)
case _ => None
}
None: Option[Seq[Int]]