这个项目有MVVM、Room、Koin和Coroutines。
项目代码:
@Dao
interface MovieDao {
@get:Query("select poster_path from Movie")
val getImgPopularMovieList: LiveData<List<String>>
}在DAO接口中,"@get:Query“代替"@Query”和"val“而不是”趣味“是什么意思?
以及如何添加WHERE子句,而不使用函数传递参数或使用常量?(使用强制val代替乐趣)。示例:“从电影中选择poster_path类别= :someParameterOrConstant”
发布于 2020-10-09 00:30:33
我想留下这个答案,以防像我这样的Kotlin新来的人遇到这个问题。
我当时正在学习关于Android的codelab,在项目中提到了@get:Query,这让我想到了这个问题。经过一项很好的研究后,我发现这个概念与使用地点目标相关,而不是使用地点目标注释。
注释使用-站点目标
简单地说,注释使用站点目标允许源代码中的任何@Annotations在编译后的字节码中或在kapt生成的@Annotations代码中处于非常特定的位置。
Kotlin支持与以下相应的使用站点目标的下列值:
让我们使用简单的类:
class Example(@param:ColorRes val resId:Int )我们使用了param的use和@ColorRes,它将@ColorRes应用于生成的Java类中的构造函数参数:
public final class Example {
private final int resId;
public final int getResId() {
return this.resId;
}
public Example(@ColorRes int resId) {
this.resId = resId;
}
}让我们将使用站点更改为field。
class Example(@field:ColorRes val resId:Int )现在,@ColorRes注释将应用于生成类的resId字段:
public final class Example {
@ColorRes
private final int resId;
public final int getResId() {
return this.resId;
}
public ViewModel(int resId) {
this.resId = resId;
}
}通过使用get的使用站点
class Example(@get:ColorRes val resId:Int )resId字段的getter方法将具有@ColorRes注释:
public final class Example {
private final int resId;
@ColorRes
public final int getResId() {
return this.resId;
}
public Example(int resId) {
this.resId = resId;
}
}所以!
在我们的Android代码中:
@Dao
interface MovieDao {
@get:Query("select poster_path from Movie")
val popularMovieImageList: LiveData<List<String>>
}get的注释使用站点将需要MovieDao的实现将Query("...")应用于popularMovieImageList的getter方法。
public final class MovieDaoImpl {
private final LiveData<List<String>> popularMovieImageList;
@Query("select poster_path from Movie")
public final LiveData<List<String>> getPopularMovieImageList() {
...
}
}注意到:以前的java代码是我想象中的,我不知道Room为这个Dao生成的实现会是什么样子,只是为了支持我的解释。
到目前为止!
为什么@get:Query而不是@Query
那么,从安卓的文档中,我们将@Query用于方法:
将
Dao注释类中的方法标记为查询方法。
从Kotlin的文档中,我们不对方法使用Annotation Use-site targets,而是对a property or a primary constructor parameter使用
在注释属性或主构造函数参数时,有多个Java元素是从相应的Kotlin元素生成的,因此在生成的Java字节码中有多个可能的注释位置。
据我在Kotlin中学到的,属性getter不能有参数,而是使用方法。
我认为其他的困惑现在应该都清楚了。
参考文献:
https://stackoverflow.com/questions/62546062
复制相似问题