https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

Tony Blundell

06/18/2020, 8:54 PM
Hi, is anyone able to help me with the correct syntax here please? I have the following class, which basically gets a JSON string from AWS, then converts it to an instance of a data class...
Copy code
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...
Copy code
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?
a

araqnid

06/18/2020, 9:44 PM
Usually I’d make a public member function that takes a java Class or a KClass, and then an inline function/extension function with a reified type parameter that just calls the member with T::class.java
w

Wesley Acheson

06/19/2020, 11:38 AM
Well sounds like you kind of have a design issue. You want to read as a type, and the type has a private member. But you want to access as the member. Right?
t

Tony Blundell

06/23/2020, 6:51 PM
Thanks both! Not quite @Wesley Acheson, private member's are on the class, not the type.
8 Views