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
相关产品推荐
相关产品推荐

