kotlin DSL 从其他文件中检索密钥

OLe*_*ert 2 android kotlin build.gradle gradle-kotlin-dsl

我正在尝试将我的 gradle 文件切换到 Kotlin DSL。我的项目正在调用 API。

build.gradle(app)我有一个函数来检索存储在另一个文件中的 api 密钥keys.properties

在出现一些问题(例如)之后,我重写了函数以获取密钥。我在中编写了以下函数build.gradle.kts

import import java.io.File

fun readFileLineByLineUsingForEachLine2(fileName: String): HashMap<String, String>{
    val items = HashMap<String, String>()

    File(fileName).forEachLine {
        items[it.split("=")[0]] = it.split("=")[1]
    }

    return items
}
Run Code Online (Sandbox Code Playgroud)

然后我设置一个变量来保存特定键的值:

buildConfigField(String!, "API_KEY", returnMapOfKeys()["API_KEY"])
Run Code Online (Sandbox Code Playgroud)

修复了一些错误后,我遇到了以下问题:

app/build.gradle.kts:49:36: Expecting ')'
Run Code Online (Sandbox Code Playgroud)

上面带有buildConfigField.

有人知道这个错误在哪里吗?

或者有人知道如何使用 Kotlin DSL 从文件中检索密钥?

OLe*_*ert 5

我解决了我的问题(似乎是这样......检查编辑!!)。我最终得到了以下功能:

// Retrieve key for api
fun getApiKey(): String {
    val items = HashMap<String, String>()
    val f = File("keys.properties")

    f.forEachLine {
        items[it.split("=")[0]] = it.split("=")[1]
    }

    return items["API_KEY"]!!
}
Run Code Online (Sandbox Code Playgroud)

然后我调用buildConfigField如下:

buildConfigField("String", "API_KEY", getApiKey())
Run Code Online (Sandbox Code Playgroud)

这部分不再有错误。

编辑

一旦我修复了 中的所有错误build.gradle.kts,我的项目构建就会返回keys.properties找不到文件:我必须修复我的函数getApiKey。最后,我可以使用以下实现来构建和运行我的项目:

// Return value of api key stored in `app/keys.properties`
fun getApiKey(): String {
    val items = HashMap<String, String>()

    val fl = rootProject.file("app/keys.properties")

    (fl.exists())?.let {
        fl.forEachLine {
            items[it.split("=")[0]] = it.split("=")[1]
        }
    }

    return items["API_KEY"]!!
}
Run Code Online (Sandbox Code Playgroud)

这个函数对于它所有的硬编码内容来说还算不错,但它允许构建我的项目。