Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading