In kotlin-reflect
, class KParameter
has nullable name
, and its KDoc says:
Name of this parameter as it was declared in the source code, or
null
if the parameter has no name or its name is not available at runtime. Examples of nameless parameters include this instance for member functions, extension receiver for extension functions or properties, parameters of Java methods compiled without the debug information, and others.
It says about well-known fact that Java doesn't always include parameter names in bytecode, but it says nothing about Kotlin classes, though there are some others.
Can I assume that Kotlin compiler retains parameter names declared for functions in Kotlin sources? (In particular, I need constructor parameter names).
When targeting the JVM, Kotlin produces Java compatible bytecode. When targeting JavaScript, Kotlin transpiles to ES5. 1 and generates code which is compatible with module systems including AMD and CommonJS. When targeting native, Kotlin will produce platform-specific code (via LLVM).
The Kotlin compiler for JVM compiles Kotlin source files into Java class files.
Unless the bytecode was modified in some way, it's safe to assume that all parameters which are given names in the sources will have those names at runtime. This is true for Kotlin 1.0 and there's no plans to change this.
If you're interested which unnamed parameters does others include, there's also the single parameter of a default property setter and the outer class parameter for an inner class constructor. Such parameters don't have names neither in the source code nor at runtime.
UPD: since this may seem confusing to some, this question and the answer are only related to retaining parameter names for Kotlin reflection and specifically so that KParameter.name
would work. This is not related to the parameter names that Java reflection would see for compiled Kotlin code. To retain parameter names for Java reflection, pass the -java-parameters
option to the Kotlin compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With