An Annotation argument must be a compile time constant

為{幸葍}努か 提交于 2019-12-01 00:32:11

问题


i have seen this question. Similar error.But in my case it is different.

While working with Room i was creating table. it was working fine.

@Daointerface 
UserDao {
@Query("SELECT * FROM user")
fun getAll(): List<User>

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(user: User)

@Delete
fun delete(user: User)}

but then i found all table Names must be stored in a different class. like table name "user" - > Stored in different class.

Eg.

class Table {
companion object {
    const val USER_TABLE = "user"
}}

But below code is not working . it is not picking up table name from Table class. Giving compile time error . "An Annotation argument must be a compile time constant" please help me out.What wrong in it

@Query("SELECT * FROM $Table.USER_TABLE")
fun getAll(): List<User>

回答1:


The problem is the one stated in the error, you can't have dynamically defined arguments for your @Query annotation. If you want to define the name of the table somewhere else, use string concatenation. You can do it like this:

@Query("SELECT * FROM " + Table.USER_TABLE)
fun getAll(): List<User>

This is how they do it in this google sample.




回答2:


You need to escape the String concatenation when using @Value annotation with the dollar symbol in Kotlin (prepend \ to $):

@Query("SELECT * FROM \$Table.USER_TABLE")
fun getAll(): List<User>



回答3:


You should define column name also in data class and access if you want to use columns in queries and access it via this method:

@Query("SELECT * FROM ${Table.USER_TABLE}")


来源:https://stackoverflow.com/questions/50678667/an-annotation-argument-must-be-a-compile-time-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!