Search code examples
scalaapache-beam

How to use Beam's PAssert.that(foo).satisfies(bar) in Scala?


The Beam Java API has a PAssert method satisfies which takes a function of type SerializableFunction<Iterable<T>, Void>

However, Java's Void isn't exactly the same as Scala's Unit, so the compiler complains if you pass something like PAssert.that(foo).satisfies(contents => contents.forEach(_.someListProperty.nonEmpty)).

You can add a asInstanceOf[Null] at the end of the forEach to get rid of the compilation error, but then it throws a runtime exception saying that it cannot cast the class to null.

If you also just explicitly return null at the end of the function, the test always evaluates to true, even if the predicate was false.

How can one use this function? Or is there another way to test that each individual element of a resulting PCollection satisfies a condition?


Solution

  • This quote from your question is the core issue:

    If you also just explicitly return null at the end of the function, the test always evaluates to true, even if the predicate was false.

    The idea of the function is that it should throw an exception if there is a problem, for example by using assertion methods. So your approach of adding an explicit return null at the end is the right way to use this directly in Scala. Adding a nice wrapper as in the other answer is good, too.