https://kotlinlang.org logo
#reflect
Title
# reflect
d

dstarcev

04/19/2018, 9:57 AM
How do I find check if a constructor parameter is also a property?
u

udalov

04/19/2018, 9:58 AM
Manually, i.e. find a property with the same name
We consider being declared in a primary constructor an internal implementation detail of a property, so there's no information in the binary metadata to differentiate between
Copy code
class A(val x: String)
and
Copy code
class A(x: String) {
    val x: String = x
}
d

dstarcev

04/19/2018, 10:03 AM
How do I differentiate
Copy code
class A(x: String) {
    val x: String = x
}
and
Copy code
class A(x: String) {
    val x: String = "not x"
}
?
u

udalov

04/19/2018, 10:06 AM
You can't do that either, because of the reason I described. Basically, to the outside observer, a class has primary constructor parameters and properties but it cannot tell how they are related. But this is not a bug, it's by design at the moment. Do you have a use case where it's necessary to know if a property is declared in the constructor?
d

dstarcev

04/19/2018, 10:08 AM
Obfuscating a class I want to keep the same names for parameters of the primary constructor and their according properties if such
otherwise kotlin reflection will be broken on the class, as @Eugenio said in another thread
or at least tools such as Jackson that may rely on these names may break
u

udalov

04/19/2018, 10:11 AM
No, the question in that thread was whether Kotlin reflection would break if the property name differs from the backing field name (at least that's what I was answering :) ). Nothing would break if the property name differs from the "related" primary constructor parameter name, because as I said, there's no information on that relation after the class is compiled, so no tool can rely upon it
e

Eugenio

04/19/2018, 1:45 PM
Isn't there a way to keep the parameter names when compiling for Java8?
u

udalov

04/19/2018, 2:16 PM
There is (
-java-parameters
), but I don't see how it's relevant to this discussion because here only the Kotlin metadata is affected
3 Views