Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin compiler always retain parameter names in bytecode?

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).

like image 558
hotkey Avatar asked Mar 18 '16 19:03

hotkey


People also ask

How does the Kotlin compiler work?

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).

Does Kotlin compile to Java or bytecode?

The Kotlin compiler for JVM compiles Kotlin source files into Java class files.


1 Answers

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.

like image 167
Alexander Udalov Avatar answered Sep 26 '22 22:09

Alexander Udalov