https://kotlinlang.org logo
#getting-started
Title
# getting-started
z

Zinedine Bedrani

07/19/2022, 6:58 PM
Playing with Reflection API and property reference I tried something like this :
Copy code
data class Point(val x:Int, val y:Int)

 val p = Point(5,13)

   val getter1 = Point::x
   val getter2: (Point) -> Int  = Point::x
 
    println(getter1(p)) // 5
    println(getter2(p)) // 5
What I don’t understand is why with getter1 I was able to get reflection information about x for example I could do something like :
Copy code
println(getter1.visibility) // PUBLIC
   println(getter1.returnType) // <http://kotlin.Int|kotlin.Int>
while with getter2 I can’t, even if I use the
@OptIn(ExperimentalReflectionOnLambdas::class)
with
println(getter2.reflect()?.returnType)
the result is null.
j

Joffrey

07/19/2022, 7:03 PM
The types of
getter1
and
getter2
are not the same. By specifying a wider type on
getter2
, you're losing the specificities of the more precise type of
Point::x
(
KProperty1<Point, Int>
). Using the actual
KProperty
type comes with extra information. A simple analogy would be
val getter3: Any = Point::x
- do you expect to be able to access
visibility
and
returnType
here?
Using
.reflect()
on the
getter2
function will just give you a
KFunction
, not really information about the actual property
x
z

Zinedine Bedrani

07/19/2022, 7:08 PM
No I don’t Expect that but
(Point) -> Int
is a function type, so r`eflect()` should return
KFunction
, isn’t it ? so I don’t understand why reflect() doesn’t return
KProperty.Getter
in this case, or Am I wrong ?
Ah OK I see
5 Views