【问题标题】:Why does Room insert method not accept an Iterable?为什么 Room insert 方法不接受 Iterable?
【发布时间】:2020-03-28 23:23:39
【问题描述】:

我可以编译代码:

@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为什么?

【问题讨论】:

  • 您是否尝试过使插入方法无效?原因 List 显示错误。
  • 是的,void insert(Iterable&lt;T&gt; objects) 不会在编译时产生错误,但是为什么updateinsert 方法的接口会有这样的差异!?

标签: android collections insert android-room iterable


【解决方案1】:

一、为什么不能插入:
它是关于 Java 的“继承”和“多态”的 `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

【讨论】:

  • 我了解您的First,但不明白Room 设计者在库中的insertupdate 之间做出了如此大的区别。 Secondary:如果没有缩小可接受参数类的原因,我想使用Room-library 代码并向开发人员写一个错误报告。
猜你喜欢
  • 2012-01-18
  • 2014-12-24
  • 2014-05-31
  • 2011-08-23
  • 2016-03-24
  • 2020-07-28
  • 2017-08-17
相关资源
最近更新 更多