I am trying to write a while loop in a functional way in scala. What I want to do is populate a list with the messages from a queue (Kafka in this case but doesn't really matter).
I'm doing this for an integration test and since Kafka is running remotely when the tests are running in CI, the test fails some times because Kafka does not return any messages. So I wrote a loop that will query Kafka until I get back all the results I expect (otherwise the test will timeout after a while and fail). I have this right now:
var result = List[Int]()
while (result.size < expectedNumberOfMessages) {
result = result ++ kafkaConsumer.poll(Duration.ofSeconds(10)).records(KAFKA_TOPIC).iterator().toList.map(_.value.getPayload)
}
This works fine but it looks horrible to me. Plus if it was production code it would also be inefficient. Can anyone suggest a better way of doing this functionally?