0

I have the following class, which basically gets a JSON string from AWS, then converts it to an instance of a data class...

class SecretsManager(region: String) {
    private val gson = Gson()
    private val smClient = AWSSecretsManagerClientBuilder.standard().withRegion(region).build()

    fun <T> getSecret(id: String): T {
        val req = GetSecretValueRequest().withSecretId(id)
        val json = smClient.getSecretValue(req).getSecretString()
        return gson.fromJson(json, T::class.java)
    }
}

To be used like this...

val myInstance = SecretsManager("eu-west-2").getSecret<MyDataClass>("myId")

Currently, I get an error - Cannot use 'T' as reified type parameter. I can get around this by marking the function as inline and T as reified , but then I can't access the private attributes from within the function.

What's the best way to do this in Kotlin?

2
  • 1
    You can't access the class of a type parameter, since they're erased. If you don't want to make T reified, accept a Class<T> as a parameter Commented Jun 18, 2020 at 21:31
  • add Class parameter to current function fun <T> getSecret(id: String, clazz: Class<T>): T and create overloaded function inline fun <reified T> getSecret(id: String): T = getSecret(id: String, T::class.java) Commented Jun 18, 2020 at 21:37

1 Answer 1

1

You need to add another parameter to the getSecret method, and also need to add an inline reified method for that to work. See the code below

class SecretsManager(region: String) {
    private val gson = Gson()
    private val smClient = AWSSecretsManagerClientBuilder.standard().withRegion(region).build()

    fun <T> getSecret(type: Class<T>, id: String): T {
        val req = GetSecretValueRequest().withSecretId(id)
        val json = smClient.getSecretValue(req).getSecretString()
        return gson.fromJson(json, type)
    }

    inline fun <reified T> getSecret(id: String): T = getSecret(T::class.java, id)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.