Data class constructor arguments unnamed at runtime

While trying to make a serialization system that automatically detects constructors with similarly named and typed arguments to the fields serialized I ran into the fact that data class constructor arguments don’t seem to carry names. When I decompile they have names, but I presume that’s a kotlin-specific metadata thing.

Here is my test code:

fun main(args: Array<String>) {
    val ctorStr = MyCoolClass::class.java
            .declaredConstructors.first()
            .parameters.map { it.type.simpleName + " " + it.name + if (it.isNamePresent) "" else "!" }
            .joinToString(", ")

    println("constructor(" + ctorStr + ")")
}

class MyCoolClass(val a: Int, val b: Int, val c: String)

If the parameters carried their names it would print constructor(int a, int b, String c), but instead it prints constructor(int arg0!, int arg1!, String arg2!), meaning that none of the arguments had names at runtime.

Kotlin 1.0 generates Java 6 bytecode and never generates parameter names for any methods. An option to generate parameter names in the bytecode is added in Kotlin 1.1.

1 Like

Ah, TIL J6 doesn’t support parameter names. Makes sense now. :thumbsup: