Kotlin 1.7.0 中的 Android Room

Arn*_*r Z 5 android kotlin kapt android-room kotlin-symbol-processing

当更新到 Kotlin 1.7.0 时,由于最新版本的 Jetpack Compose 需要它,我发现 Room 不再工作。我使用kapt作为我的注释处理器,编译器抛出错误消息,例如:

[*] error: Query method parameters should either be a type that can be converted into a database column or a List / Array that contains such type. You can consider adding a Type Adapter for this.
Run Code Online (Sandbox Code Playgroud)

Arn*_*r Z 10

修复方法是从 迁移kaptksp. KSP 理论上是 kapt 的继承者,由 Google 开发。为此,首先我必须将库导入到我的类路径中:

buildscript {
  ...
  repositories {
    ...
    classpath "com.google.devtools.ksp:com.google.devtools.ksp.gradle.plugin:1.7.0-1.0.6"
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

从MVN 存储库检查最新版本,以防万一有更新,但在撰写本文时,Kotlin 1.7.0 的最新版本是1.7.0-1.0.6

现在,在我的模块中build.gradle

plugins {
  ...

  // Remove the old kapt plugin
  id 'org.jetbrains.kotlin.kapt'

  // Add the new KSP plugin
  id 'com.google.devtools.ksp'

  ...
}

...

android {
  ...
  defaultConfig {
    ...
    // Replace old compile options
    javaCompileOptions {
      annotationProcessorOptions {
        arguments += [ "room.schemaLocation": "$projectDir/schemas".toString() ]
      }
    }
    // With the new KSP arg method
    ksp {
      arg("room.schemaLocation", "$projectDir/schemas".toString())
    }
    ...
  }
  ...
}

...

dependencies {
  ...
  // Replace all kapt calls with ksp
  // kapt "androidx.room:room-compiler:$room_version"
  ksp "androidx.room:room-compiler:$room_version"
}
Run Code Online (Sandbox Code Playgroud)

现在 Room 应该可以在 Kotlin 1.7.0 中正常工作了!