How to filter out all valid typed values from an optional typed array in Ballerina

How to filter all valid typed values from an optional typed array in Ballerina? This can be done using foreach like below,

int?[] input = [1, 2, (), 3, 4, ()];
int[] output = [];
foreach int? i in input {
    if (i is int) {
        output.push(i);
    }
}

But, how to achieve this using filter? I tried the below, but it gives a compilation error,

int?[] input = [1, 2, (), 3, 4, ()];
int[] output = input.filter(i => (i is int));

What am I doing wrong here? Appreciate the help 🙂

>Solution :

filter works on an array of T to construct another array of T. It is not possible to change the type of the new (filtered) array since the predicate function may return true for any of the members from the original array.

You could use a query expression instead.

int[] output = from int? i in input where i is int select i;

Leave a Reply