如何修复Kotlin Dao中UPDATE查询方法的返回值错误
解决Room Dao中UPDATE查询返回类型错误的问题
错误原因
Room框架对UPDATE、DELETE这类修改型DAO方法有明确的返回类型限制:只能是void(对应Kotlin中的Unit)或者Int(表示操作影响的行数),你的方法返回了Object,违反了这个规则。
正确写法示例
1. 返回受影响行数(推荐)
如果需要知道本次更新操作修改了多少条数据,将返回类型改为Int:
@Dao interface YourDao { @Query("UPDATE your_table SET column1 = :newValue WHERE id = :targetId") fun updateItem(targetId: Int, newValue: String): Int }
2. 不返回结果
如果不需要关注受影响行数,使用Unit(Kotlin中可省略,默认返回Unit):
@Dao interface YourDao { @Query("UPDATE your_table SET column1 = :newValue WHERE id = :targetId") fun updateItem(targetId: Int, newValue: String) // 显式写Unit也可以:fun updateItem(targetId: Int, newValue: String): Unit }
协程场景适配
如果使用协程执行异步操作,只需给方法加上suspend修饰符,返回类型仍遵循上述规则:
@Dao interface YourDao { @Query("UPDATE your_table SET column1 = :newValue WHERE id = :targetId") suspend fun updateItem(targetId: Int, newValue: String): Int }
内容的提问来源于stack exchange,提问作者Karlen Legaspi
相关产品推荐
相关产品推荐

