How to check if an object exists in an array in Ballerina

48 Views Asked by At

I want to know how to check if a particular object already exists in an array.

I tried with following approach and it gives a compile time error.

import ballerina/io;

class A {
    private int a = 2;
}


public function main() {
    A a = new;
    A[] arr1 = [a, a, a];
    A[] arr2 = [new , new, new];

    io:println(arr1.indexOf(a) != ());
}

Error:

ERROR [main.bal:(29:16,29:20)] incompatible types: expected 'ballerina/lang.array:0.0.0:AnydataType[]', found 'A[]'
ERROR [main.bal:(29:29,29:30)] incompatible types: expected 'ballerina/lang.array:0.0.0:AnydataType', found 'A'
error: compilation contains errors
1

There are 1 best solutions below

0
On

array:indexOf is based on deep (value) equality, and therefore, is defined only for anydata values (for which deep equality is defined). The variable a contains an object, which is not anydata, and therefore, you can't use indexOf with it.

You can use following method to achieve the task

import ballerina/io;

class A {
    private int a = 2;
}


public function main() {
    A a = new;
    A[] arr1 = [a, a, a];
    A[] arr2 = [new , new, new];

    io:println(arr1.some(element => element === a)); // true
    io:println(arr2.some(element => element === a)); // false
}