https://kotlinlang.org logo
d

Derek Peirce

02/26/2022, 4:27 AM
Is there any plan for implementing compile-time reflection, at least at a basic level? I've asked about it here before, but recently I've been running into more places where I want to pass, for example, both a getter and setter for a property into a method, and this would be burdensome:
Copy code
applyMutation({ x }, { x = it })
I would much rather be able to pass in the property to the inline method, and have the getter and setter be derived from it automatically when inlining:
Copy code
applyMutation(::x)
but we currently instead end up with terribly inefficient (compared to direct accesses) `KMutableProperty0`s.
👍 1
j

jw

02/26/2022, 4:29 AM
This was one of the things I was hoping to pursue while at Google before I left. I was thinking a good start would be a syntax
x::get
and
x::set
which would produce the two lambdas from the first snippet automatically.
Passing a "whole" property (with both getter and setter) is much more complicated from a design standpoint if you want to remain efficient
d

Derek Peirce

02/26/2022, 4:44 AM
x::get
and
x::set
would certainly be useful. For the property, I'd effectively hope that as the method is inlined, it would note that because the property was
::x
, a call to
get
becomes
x
, and a call to
set
becomes
x =
., and in the end the property object isn't involved at all, similar to lambda objects. It would also be nice if it could inline enough that something like
javaField.name
to be known at compilation-time as
"x"
, though that would probably have to be added to the
KProperty
interface directly to be reasonably inline-able. (Ideally, it would eventually be powerful enough that methods like
equals
and
toString
could be derived entirely by the compiler even without
data
.)
e

ephemient

02/26/2022, 5:11 AM
kotlin reflection doesn't look that bad to me. with this really dumb microbenchmark, I get results
Copy code
Benchmark                          Mode  Cnt    Score    Error  Units
ReflectionBench.javaReflection    thrpt    5  163.525 ±  1.796  ops/s
ReflectionBench.kotlinReflection  thrpt    5  555.280 ± 88.205  ops/s
ReflectionBench.methodHandle      thrpt    5  135.869 ±  1.506  ops/s
ReflectionBench.noReflection      thrpt    5  453.034 ± 10.804  ops/s
d

dmitriy.novozhilov

02/26/2022, 9:50 AM
You can take a look at Reflekt, whcih provides compile-time reflection via compiler plugin https://github.com/JetBrains-Research/reflekt
d

Derek Peirce

02/27/2022, 8:47 AM
Reflekt looks very interesting, are there any ventures into compile-time reflection that optimizes existing uses of reflection such as
KProperty
in addition to creating a separate lookup library?
d

dmitriy.novozhilov

02/27/2022, 9:29 AM
No at this point, as I know
2 Views