kotlin DSL retrieving keys from other file

ぐ巨炮叔叔 提交于 2020-01-16 08:35:28

问题


I am trying to switch my gradle files to Kotlin DSL. My project is making call to an API.

In build.gradle(app) I had a function to retrieve an api key stored in an other file keys.properties.

After some problem (for example) I rewrote the function to get the key. I wrote the following function in 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
}

Then I set a variable to hold the value of a particular key:

buildConfigField(String!, "API_KEY", returnMapOfKeys()["API_KEY"])

After fixing some errors I am stuck with the following one:

app/build.gradle.kts:49:36: Expecting ')'

which point on the line above with buildConfigField.

Does someone know where is this error ?

Or does someone know how to retrieve keys from files with Kotlin DSL ?


回答1:


I solved my problem (it seems so.. check the edit!!). I ended up with the following function:

// 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"]!!
}

And then I call buildConfigField as follow:

buildConfigField("String", "API_KEY", getApiKey())

There are no errors anymore on this part.

Edit

Once I have fixed all errors in the build.gradle.kts, the build of my project return that the file keys.properties could not be found: I had to fix my function getApiKey. Finally I could build and run my project with the following implementation:

// 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"]!!
}

This function is far to be good with all its hardcoded stuff but it allows to build my project.



来源:https://stackoverflow.com/questions/59052655/kotlin-dsl-retrieving-keys-from-other-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!