如何解析 Kotlin 中 Room 库的注解?

How do I resolve annotations for Room library in Kotlin?

我正在关注 this tutorial 的 Room for SQLite in kotlin。这是他们拥有用户实体的第一步

@Entity
data class User(
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "first_name") val firstName: String?,
    @ColumnInfo(name = "last_name") val lastName: String?
)

我在所有这些注释上收到 IDE 个未解析引用错误。

我对此完全陌生。我找不到任何关于如何在 Kotlin 中注释的信息。基本上,我不知道如何在 Kotlin 中进行注释。

我需要依赖库吗?

发生这种错误是因为您没有在 build.gradle 中声明依赖项。

此外,如您发送的页面中所述:

Note: In order to use Room in your app, declare Room dependencies in your app's build.gradle file.

可以找到依赖列表here

因此,按如下方式将 Room 依赖项添加到您的 build.gradle(您可以一个一个地添加并检查哪个解决了问题:

dependencies {
  def room_version = "2.2.2"

  implementation "androidx.room:room-runtime:$room_version"
  annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

  // optional - Kotlin Extensions and Coroutines support for Room
  implementation "androidx.room:room-ktx:$room_version"

  // optional - RxJava support for Room
  implementation "androidx.room:room-rxjava2:$room_version"

  // optional - Guava support for Room, including Optional and ListenableFuture
  implementation "androidx.room:room-guava:$room_version"

  // Test helpers
  testImplementation "androidx.room:room-testing:$room_version"
}

添加它们并执行同步。然后,这些错误应该消失了