首页 > 解决方案 > 为什么 Room insert 方法不接受 Iterable?

问题描述

我可以编译代码:

@Update 
public abstract int update(Iterable<T> objects);

但是当我尝试编译时

@Insert(onConflict = OnConflictStrategy.IGNORE)
public abstract List<Long> insert(Iterable<T> objects);

编译器有一条消息:

error: no suitable method found for insertAndReturnIdsList(Iterable<SessionKey>)
method EntityInsertionAdapter.insertAndReturnIdsList(SessionKey[]) is not applicable
(argument mismatch; Iterable<SessionKey> cannot be converted to SessionKey[])
method EntityInsertionAdapter.insertAndReturnIdsList(Collection<? extends SessionKey>) is not applicable
(argument mismatch; Iterable<SessionKey> cannot be converted to Collection<? extends SessionKey>)

正如我所发现的,androidx.room.EntityInsertionAdapter需要Collection作为一个论点:

List<Long> insertAndReturnIdsList(Collection<? extends T> entities)

而不是Iterable. 为什么?

标签: androidcollectionsinsertandroid-roomiterable

解决方案


首先,为什么你不能插入:
它是关于 Java `Inheritance` 和 `Polymorphism` `Collection` 是 `Iterable` 的儿子,你可以传递 `Collection` 子类实例但不能传递 `Iterable`


其次,为什么可以更新EntityDeletionOrUpdateAdapter源代码是

public final int handleMultiple(Iterable<? extends T> entities) {
    final SupportSQLiteStatement stmt = acquire();
    try {
        int total = 0;
        for (T entity : entities) {
            bind(stmt, entity);
            total += stmt.executeUpdateDelete();
        }
        return total;
    } finally {
        release(stmt);
    }
}

参数Iterable不是Collection


推荐阅读