Any ideas how to create a `data class` using param...
# announcements
g
Any ideas how to create a
data class
using parameters? I'm thinking of doing it with a map of values, but if there's a constructor method I could call, that would be great.
d
Can you clarify what you mean by "using parameters"? Do you mean you have a map of name to parameter value?
👍 1
g
That's right, a map of names and types.
d
Copy code
data class Person(val name: String, val age: Int)

fun main() {
    val args = mapOf("name" to "Peter", "age" to 23)
    val constructor = Person::class.primaryConstructor!!
    val person = constructor.callBy(
        constructor.parameters.associateWith { args[it.name] }
    )
    println(person)
}
🤔 1
Note that this requires kotlin-reflect
g
I haven't used the kotlin-reflect features in depth, apart from the ::class function. Do I have to import an addition kotlin-reflect feature? I can't get this code to run..
d
What error do you get?
g
unresolved reference: primaryConstructor
d
Yes, you need to have
kotlin-reflect
on the classpath (
compile 'org.jetbrains.kotlin:kotlin-reflect'
when using Gradle).
g
Ah, I'm installing it now...
Another unresolved reference in line
constructor.parameters.associateWith { args[it.name]
associateWith does not exist
d
It was added in 1.3, you can use
associate { it to args[it.name] }
for 1.2.x instead
g
That's works for me. I'll need to update my Kt version for future reference...
s
also if you are using the kotlin dsl you can shorten the kotlin-reflect declaration to just
implementation(kotlin("reflect"))