android - 为什么 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
. 为什么?
解决方案
首先,为什么你不能插入:
它是关于 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
推荐阅读
- javascript - 如何在 Javascript 中测试 google.protobuf.Timestamp?
- three.js - 将点从正方形更改为矩形
- r - 如何生成系列中的前 n 项:
- ruby-on-rails - Cron 工作在开发中的任何时候都不起作用
- html - 将 svg 元素包裹在圆圈中,而无需使用 javascript
- cplex - Cplex(小数位数)
- java - 滚动时无法单击列表视图中的按钮
- wpf - 是否有任何控件不是从 WPF 中的依赖对象派生的?
- python - 如何打破 python 中的 try 循环?
- android - 当我的应用程序既不在后台运行也不在前台运行时,如何让我的应用程序获取(事务性)SMS?