You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:56:59