Sink Operations
In previous sections, we learned how to create and use sinks. Now, let’s explore some operations that let you transform or filter sink behavior.
At times, you may have a sink that works with one type of input, but your current stream uses a different type. The Sink.mapInput
function helps you adapt your sink to a new input type by transforming the input values. While Sink.map
changes the sink’s output, Sink.mapInput
changes the input it accepts.
Example (Converting String Input to Numeric for Summing)
Suppose you have a Sink.sum
that calculates the sum of numbers. If your stream contains strings rather than numbers, Sink.mapInput
can convert those strings into numbers, allowing Sink.sum
to work with your stream:
When you need to transform both the input and output of a sink, Sink.dimap
provides a flexible solution. It extends mapInput
by allowing you to transform the input type, perform the operation, and then transform the output to a new type. This can be useful for complete conversions between input and output types.
Example (Converting Input to Integer, Summing, and Converting Output to String)
Sinks can also filter incoming elements based on specific conditions with Sink.filterInput
. This operation allows the sink to process only elements that meet certain criteria.
Example (Filtering Negative Numbers in Chunks of Three)
In the example below, elements are collected in chunks of three, but only positive numbers are included: