Kotlin ... in function parameters, e.g. from Java - setFilterById(long... ids)

205 Views Asked by At

In Android DownloadManager class, for example, there is a function declared in Java as:

    private long[] mIds = null;

    public Query setFilterById(long... ids) {
        mIds = ids;
        return this;
    }

In Java I can pass to it an array of long values, and it works great. In Kotlin, when I try:

    val mEnqued = ArrayList<Long>()
    // collect download ids to mEnqued...
    query.setFilterById(mEnqued.toLongArray())
    // or try to pass an array of long created in any other way...
    // it will take: query.setFilterById(7L, 15L, 234L) - but it's useless

Kotlin compiler complains "Type mismatch: inferred type is LongArray but Long was expected"... How else I could pass to this function a list or array of long Id values? I cannot type them directly in the source code, because in advance I have no idea how many of them there will be, or what will be their values? Kotlin seems to be very limited or "brain damaged" here...

1

There are 1 best solutions below

0
On

Kotlin has the spread operator to deliver an array as list of single parameters to a vararg function:

query.setFilterById(*mEnqued.toLongArray())

See also Kotlin documentation