首页 > 解决方案 > Kotlin ... 在函数参数中,例如来自 Java - setFilterById(long... ids)

问题描述

例如,在 Android DownloadManager 类中,有一个用 Java 声明的函数:

    private long[] mIds = null;

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

在 Java 中,我可以将一个 long 值数组传递给它,并且效果很好。在 Kotlin 中,当我尝试:

    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 编译器抱怨“类型不匹配:推断的类型是 LongArray 但预计为 Long”......我还能如何将 long Id 值的列表或数组传递给这个函数?我不能直接在源代码中输入它们,因为事先我不知道它们中有多少,或者它们的值是什么?Kotlin 在这里似乎非常有限或“大脑受损”......

标签: kotlinvariadic-functionsfunction-parameter

解决方案


Kotlin 使用扩展运算符将数组作为单个参数列表传递给vararg函数:

query.setFilterById(*mEnqued.toLongArray())

另请参阅Kotlin 文档


推荐阅读