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

Kotlin中@Query注解不适用于成员函数报错求助

问题解决:ERROR: This annotation is not applicable to target 'member function' in Kotlin

核心原因与修复步骤

1. 确认@Query注解的正确导入

必须使用Room库专属的@Query注解,避免误导入其他框架的同名注解。正确导入路径为:

import androidx.room.Query

若导入了javax.persistence.Query这类非Room的注解,就会触发“注解不适用于成员函数”的报错。

2. 修复代码语法错误

你的第一个查询函数存在泛型声明不完整的问题:返回值缺少闭合的尖括号。
原错误代码:

fun getPriceList(): LiveData<List<CoinPriceInfo>

修正后:

fun getPriceList(): LiveData<List<CoinPriceInfo>>

语法错误会导致Room注解处理器无法正确解析函数结构,进而引发注解兼容性报错。

3. 验证Room依赖配置

确保Module级build.gradle(或build.gradle.kts)中正确配置Room相关依赖:

  • 启用Kotlin注解处理器:
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
}
  • 添加Room核心依赖(可替换为最新稳定版本):
dependencies {
    def room_version = "2.5.0"
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
    // 需使用Kotlin扩展功能时添加
    implementation "androidx.room:room-ktx:$room_version"
}

修正后的完整Dao代码

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.lifecycle.LiveData

@Dao
interface CoinPriceInfoDao {
    @Query("SELECT * FROM full_price_list ORDER BY lastupdate")
    fun getPriceList(): LiveData<List<CoinPriceInfo>>

    @Query("SELECT * FROM full_price_list WHERE fromsymbol == :fSym LIMIT 1")
    fun getPriceInfoAboutCoin(fSym: String): LiveData<CoinPriceInfo>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertPriceList(priceList: List<CoinPriceInfo>)
}

内容的提问来源于stack exchange,提问作者Kanat Bayalbayev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:42:12