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

Tianyu Zhu

10/07/2021, 4:03 PM
Is there an easy to to get the `Class`/`KClass` object of a top-level .kt file?
k

Kirill Grouchnikov

10/07/2021, 4:14 PM
What's a top level file? What if it only has functions? What if it has multiple classes in it?
t

Tianyu Zhu

10/07/2021, 4:17 PM
Suppose you declare a file named
Util.kt
with
Copy code
fun foo() { ... }
fun bar() { ... }
In Java you'd be able to access these by writing
Copy code
UtilKt.foo()
And you'd also be able to get the class:
Copy code
UtilKt.class
Can I do the same in Kotlin?
I understand that this isn't appropriate for other backends... but I'm surprised I can't do this even specifically for Kotlin/JVM
j

Joffrey

10/07/2021, 4:35 PM
I guess the wrapping class only exists so that Java can use such declarations, but is not supposed to exist from Kotlin's point of view. What is your ultimate goal here? What do you want to achieve with this class instance?
t

Tianyu Zhu

10/07/2021, 4:40 PM
I would like to list all of the utility functions in
UtilKt.class
reflectively, e.g.
Copy code
UtilKt::class.declaredFunctions
s

Scott Kruse

10/07/2021, 4:41 PM
Put them in a kotlin class?
e

ephemient

10/07/2021, 4:49 PM
not even
Copy code
Class.forName("UtilKt").kotlin.declaredFunctions
will work, as "UtilKt" is not a Kotlin class, it is a Kotlin file facade class
you may be interested in following https://youtrack.jetbrains.com/issue/KT-21599 https://youtrack.jetbrains.com/issue/KT-16479 but it doesn't look like there's any plans for them
t

Tianyu Zhu

10/07/2021, 4:54 PM
Thank you! I've bookmaked those issues for now 🙂
2 Views