https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
reflect
  • i

    Ian Stewart

    04/01/2020, 11:37 PM
    Hi; I’m trying to access the argument names of a function as a KType. If I println the ktype, I get
    (url: kotlin.String, cont: (result: kotlin.String) -> kotlin.Unit) -> kotlin.Unit
    …so the information is there, at least internally. Is there any way of getting the ‘url’ and ‘cont’ strings out? I am able to get the types from the arguments() method. I have read about using .reflect() to get a KFunction, but I cannot find a good example of how to do this. for myktype.classifier.reflect(), I get:
    Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
    public fun <R> Function<TypeVariable(R)>.reflect(): KFunction<TypeVariable(R)>? defined in kotlin.reflect.jvm
    d
    • 2
    • 5
  • m

    marcinmoskala

    04/06/2020, 3:18 PM
    Started playing with kapt, but cannot get Kotlin Reflection from
    RoundEnvironment
    . Got
    TypeElement
    but don’t have any idea how to make KClass out of that. Any ideas?
    d
    • 2
    • 2
  • j

    jeggy

    04/09/2020, 1:44 PM
    Is it possible to know if a type is a sealed class from a
    KType
    ? I've created a sample of what I'm trying to do: https://pl.kotl.in/zBHj3IlEi
    d
    • 2
    • 2
  • c

    christophsturm

    04/30/2020, 1:26 PM
    whats the easiest way to call a copy constructor of a data class via reflection?
    ➕ 1
    r
    • 2
    • 2
  • n

    nikolaymetchev

    07/24/2020, 2:57 PM
    Do you know how to get all inner object instances of a class e.g. get 
    Inner
     from 
    Outer::class
     . I figured out  how to do it using java reflection but I would prefer kotlin reflection.
    class Outer {
        object Inner : Any() {}
    }
    d
    • 2
    • 2
  • d

    Daniele B

    08/13/2020, 5:27 PM
    var myVar : String
        get() = functionUsingTheVariableName(::field.name)
    I would like to do this, but I get:
    Unsupported [References to variables aren't supported yet]
    any alternative?
    e
    • 2
    • 5
  • d

    Daniele B

    08/14/2020, 1:35 AM
    Can you confirm that Delegated Properties are accessed only when the variable is read. For example in this context:
    object LocalSettings : SettingsClass() {
        var myString by StringType("mytext")
    }
    
    
    open class SettingsClass {
    
        val settings = Settings()
    
        inner class StringType(defaultValue : String) {
            val default = defaultValue
            operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
                return settings.getString(property.name, default)
            }
            operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
                settings.putString(property.name, value)
            }
        }
    
    }
    can you confirmed that when the LocalSettings object is instantiated, the
    StringType
    delegate will be called only when accessing
    LocalSettings.myString
    ?
    d
    • 2
    • 2
  • d

    droid

    08/26/2020, 4:28 PM
    My app started crashing on
    Android 6
    devices after enabling
    R8
    with this error:
    ReflectKotlinClass.kt line 1 
    kotlin.reflect.jvm.internal.impl.descriptors.runtime.components.ReflectClassStructure.loadClassAnnotations
    Any ideas on this? It is crashing on Android 6 devices only at the moment.
    • 1
    • 1
  • j

    jaqxues

    10/15/2020, 8:09 PM
    Hello, I need to store a type (either a KClass or a KType) and was wondering whether it even make sense to want to store a simple type as KClass, or does it not matter if I have everything as KType (regarding space efficiency). Intuitively, I would not use the java-reflect-Type since it seemed more complex than simply Class, but I was wondering if that actually holds up. So what takes less space, a KClass or a KType (String::class or typeOf<String>())
    u
    • 2
    • 4
  • i

    iamthevoid

    11/02/2020, 6:40 AM
    Hey, there! Does anybody knows why property
    annotations
    for
    KClass
    returns empty array?
    g
    • 2
    • 6
  • k

    karandeep singh

    11/05/2020, 5:28 PM
    Hey everyone,
    val test by Delegate("some value")
    is it possible to get the parameter
    some value
    via reflection
    d
    • 2
    • 1
  • d

    Dario Pellegrini

    11/17/2020, 9:20 AM
    Is there a way in Kotlin to print through reflection the type o a class like Selected<Person>? The goal is to print “Selected<Person>“, but with normal reflection methods it is not possible. The only result at runtime is “Selected”.
    d
    • 2
    • 3
  • t

    tateisu

    12/18/2020, 2:11 AM
    Hi, please some one fix this
    prop.returnType.isSubtypeOf(ArrayList<String>::class.createType())
    this expression raise compile error "Only classes are allowed on the left hand side of a class literal"
    d
    • 2
    • 2
  • c

    christophsturm

    12/25/2020, 12:12 PM
    is there a way to speed up this code?
    object S {
        val string = "String"
    }
    fun main() {
        println(measureTimeMillis {
            StringProvider(S::class).getContext()
        })
    }
    class StringProvider(val kClass: KClass<*>) {
        fun getContext(): String {
            return kClass.declaredMemberProperties.single { it.name == "string" }.call(kClass.objectInstance) as String
        }
    }
    it takes 420ms on my mac
    • 1
    • 1
  • t

    Timo Gruen

    12/28/2020, 3:28 PM
    Hi Folks, i currently struggle with Kotlin Annotations and the Annotation Processor. I brought up a custom Annotation
    Property
    @Target(AnnotationTarget.PROPERTY, AnnotationTarget.PROPERTY_GETTER)
    @Retention(AnnotationRetention.RUNTIME)
    annotation class Property
    When using the annotation on a property e.g.:
    data class Example(@Property val key: String)
    and introspecting the class with a AnnotationProcessor i can find three different elements which are related to that
    key
    property. The first one is
    key
    , the second one is
    getKey
    and the third (which is currently probably the reason for my confusion) is the
    getKey$annotations()
    one, which is the only element having the annotation from java annotation processor perspective. I would have assumed that either
    key
    or
    getKey
    would also be annotated on byte-code level. Any guidance on how i can access the element
    getKey
    OR
    key
    using the annotation processor api? My actual goal is to retrieve the name
    key
    as well as the type
    String
    of the annotated element
    m
    • 2
    • 9
  • j

    jeggy

    01/07/2021, 3:56 PM
    Is it possible to get the KType of a nested sealed class? All I have access to is
    T
    and I know
    T
    is a
    Sealed Class
    .
    d
    • 2
    • 1
  • h

    holgerbrandl

    01/30/2021, 9:06 PM
    Hey there. Is there a solid way to collect all properties of a class included parent-class properties? With my current approach, it misses the fields of the parent class:
    open class Person(val name: String)
    class Manager(name: String, val isCEO:Boolean) : Person(name)
    
    val declaredMembers = Manager::class.declaredMembers
    
    val properties = declaredMembers
                .filter { it.parameters.toList().size == 1 }
                .filter { it is KProperty }
    Usecase: https://github.com/holgerbrandl/krangl/blob/60308cabde760a16fe31782c191b4799da9ba7c9/src/main/kotlin/krangl/Builder.kt#L53 where I'd like to fix it in a way that also super-class attributes are considered.
    d
    • 2
    • 2
  • h

    holgerbrandl

    02/04/2021, 10:42 PM
    With the new 1.4.30 IDE plugin,
    KFunction1.call()
    is marked as red even with the latest org.jetbrains.kotlin:kotlin-reflect:1.4.30 in the classpatth. Still, the code seems to compile fine. Or is it just me? Example
    import kotlin.reflect.KFunction1
    
    
    class Test( val funPointer: KFunction1<String, String>) {
           init{
               funPointer.call("foo")
           }
    }
    • 1
    • 2
  • p

    Patrick Jackson

    02/11/2021, 11:35 PM
    Does this usage require kotlin-reflect.jar? val getter: KMutableProperty1<> = MyClass::myProperty val my value = getter.get(myInstance)
    u
    • 2
    • 4
  • n

    nikolaymetchev

    02/22/2021, 9:14 AM
    @Marc Knaup are you saying it isn’t possible?
    e
    m
    • 3
    • 3
  • f

    Fatih Yalmanbas

    03/26/2021, 8:54 AM
    Hey guys, I have a problem using kotlin-reflect with r8 shrinker. I have tried investigating it but could not find the root cause any help would be appreciated. Please see 🧵 for more 🙂
    • 1
    • 2
  • c

    christophsturm

    03/26/2021, 11:36 AM
    kotlin reflection on the jvm seems to be 100x slower than java reflection for some usecases. is that a known issue?
    u
    • 2
    • 5
  • t

    TwoClocks

    04/16/2021, 6:02 PM
    anyone know how to compare a KType to a actual type? I want to say something like
    if( someProp.returnType == Double::class )
    In this case I could create an instance of a
    Double
    and get it's type... but pretend the type is of a class that it's not easy/possible to get an instance of easily.
    d
    • 2
    • 2
  • f

    F0X

    04/23/2021, 8:52 PM
    Is it possible to cast a value to a
    KType
    or check whether a value is of the type (or if necessary the classifier)?
    d
    • 2
    • 1
  • h

    huehnerlady

    05/18/2021, 10:26 AM
    Hi. I have a question. in the lib graphql-kotlin reflection is used to create GraphQL schema Types. If you are using a java class it will generate the types with all members being mandatory. After discussing with them they use reflection and the flag “isMarkedNullable” to determin if it is nullable or not. My question is: Why is the return type of the members of a Java class marked as non-nullable? Why is it not nullable as standard? Is there the possibility to determine if it is a javaclass or a kotlin class to work around that?
    ☑️ 1
    u
    • 2
    • 1
  • s

    Sourabh Rawat

    06/09/2021, 5:20 PM
    I want to get the name of the actual variable passed on the call site
    inline fun <reified T> foo(value: T?): T {
        println(::value.name) // get the name
    }
    
    foo(someValue) -> should output "someValue"
    foo(someValue2) -> should output "someValue2"
    I tried with https://kotlinlang.org/docs/reflection.html#property-references but to no avail. Is this even possible?
    🇳🇴 1
    r
    e
    • 3
    • 9
  • j

    jrod

    07/07/2021, 2:34 AM
    i’m trying to integrate our Android app with an sdk which uses reflection to determine which methods of a callback interface have been implemented, i.e.,
    private fun getClientMetadata(callback: EventListener?) = ClientMetadata(
        Build.VERSION.SDK_INT,
        Build.MANUFACTURER,
        Build.MODEL,
        Build.PRODUCT,
        Build.DEVICE,
        Build.HARDWARE,
        callback != null && overridesMethod(callback::class, "onLogin"),
        callback != null && overridesMethod(callback::class, "onSuccess"),
        callback != null && overridesMethod(callback::class, "onError"),
        callback != null && overridesMethod(callback::class, "onExit"),
        callback != null && overridesMethod(callback::class, "onEvent"),
    )
    
    private fun getUnixTimestamp(): Long {
        return System.currentTimeMillis()
    }
    
    private fun overridesMethod(cls: KClass<out EventListener>, methodName: String): Boolean {
        return cls.memberFunctions.first { it.name == methodName } in cls.declaredFunctions
    }
    and i’m getting the following crash:
    e
    • 2
    • 2
  • j

    jeggy

    08/02/2021, 9:12 PM
    Is it possible for me to create a function that would look something like this?
    e
    • 2
    • 4
  • t

    TwoClocks

    08/23/2021, 9:08 PM
    what's the difference between
    functions
    and
    memberFunctions
    and
    declaredFunctions
    and
    declaredMemberFunctions
    ? The docs don't point any obvious differences.
    e
    • 2
    • 2
  • h

    henrik

    10/22/2021, 9:45 AM
    From a function, can I easily resolve which function that called it?
    c
    • 2
    • 6
Powered by Linen
Title
h

henrik

10/22/2021, 9:45 AM
From a function, can I easily resolve which function that called it?
c

christophsturm

10/22/2021, 9:52 AM
Throwable().stackTrace[1].methodName
h

henrik

10/25/2021, 11:07 AM
@christophsturm Thanks!
Any idea how expensive that is?
c

christophsturm

10/25/2021, 11:09 AM
its not very expensive, but there is a newer api that you can use if you need the best performance: https://www.baeldung.com/java-9-stackwalking-api
as a rule of thumb i would use the not optimized version in test cases or in a test runner or assertion lib, but for production code i would use the stack walking
h

henrik

10/25/2021, 11:10 AM
Good to know. Thanks!
View count: 5