正在将 build.gradle 迁移到 build.gradle.Kts:无法解析属性 class

Migrating the build.gradle to build.gradle.Kts : Not able to resolve Properties class

虽然将 build.gradle 转换为 build.gradle.kts 是一个手动过程,但我在下面的代码中遇到了困难。

我多次尝试使缓存无效并重新启动工作室。但是,android.varinatFilter 无法识别。

android.variantFilter { variant ->
    if (variant.buildType.name == 'release'
            && variant.getFlavors().get(0).name == 'development') {
        variant.setIgnore(true)
    }
    if (variant.buildType.name == 'debug'
            && variant.getFlavors().get(0).name == 'production') {
        variant.setIgnore(true)
    }
}

Java.util.Properties 依赖项的属性 class 在 .kts 文件中未得到解析,Java.io 的 FileInputStream class 也未被识别。

 def getProps(path) {
        Properties props = new Properties()
        props.load(new FileInputStream(file(path)))
        return props
    }

同时应用 kotlin 注释处理器

kapt 'androidx.lifecycle:lifecycle-common-java8:2.1.0' To

kapt {'androidx.lifecycle:lifecycle-common-java8:2.1.0'} 

不起作用并且 returns 编译时错误。

如有任何帮助,我们将不胜感激。

更新

Properties class of Java.util.Properties dependency doesn't get resolved in .kts file also the FileInputStream class of Java.io is not recognized.

这将通过无效缓存和重新启动得到解决。(开始重构项目级别 gradle 然后 settings.gradle 然后 app.gradle 文件顺序)

对于 kapt {'androidx.lifecycle:lifecycle-common-java8:2.1.0'} - 请使用双引号,例如kapt {"androidx.lifecycle:lifecycle-common-java8:2.1.0"},请check details here

方法也请使用以下语法:

import java.io.FileInputStream
import java.util.Properties

/***/

fun getProps(path: String): Properties {
    val props = Properties()
    props.load(FileInputStream(file(path)))
    return props
}

变化:

  • 您需要在文件开头导入 java 个包。
  • 使用fun代替def
  • 方法需要参数类型,为此使用“:” - path: String
  • new不需要关键词
  • Variable declaration 可以以 val 开头,例如如果编译器能够理解类型,则无需手动输入。
  • Return type is mandatory 如果你的结果不是 Unit.

对于过滤器 - 我没有使用它。但是请考虑:

  • 将引号 ' 替换为 "
  • variant.getFlavors().get(0).name 替换为 variant.flavors[0].name
  • variant.setIgnore(true) 替换为 variant.ignore=true

那就是

android.variantFilter {
    if (buildType.name == "release" && flavors[0].name == "development") {
        ignore = true
    }
    if (buildType.name == "debug" && flavors[0].name == "production") {
        ignore = true
    }
}

尽管我认为

更正确的方法
flavors[0].name = "xyz"

应该是

flavors.map { it.name }.contains("xyz")