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

LeoColman

03/04/2019, 6:36 PM
Hi, how to obtain all functions that have a functional parameter using Kotlin Reflect? I tried something like
Copy code
Class.forName("myClass").declaredMethods.map { it.kotlinFunction!! }.filter { fn -> fn.parameters.any { it is KFunction<*> } }
but it didn't work
u

udalov

03/05/2019, 3:16 PM
Instead of
it is KFunction<*>
you need to check the parameter's type:
it.type.classifier == Function::class
l

LeoColman

03/05/2019, 3:47 PM
That didn't work when I tried it, but I found a solution
Copy code
fun main(args: Array<String>) {
    val funcs = Foo::class.declaredFunctions.filter { func ->
        func.parameters.any { param ->
            param.type.isSubtypeOf(Function::class.starProjectedType)
        }
    }

    println(funcs)
}

class Foo {
    fun <A> foo(fn: (A) -> Unit) {}
    fun <A, B> foo2(fn: (A, B) -> Unit) {}
    fun <A, B, C> foo3(fn: (A, B, C) -> Unit) {}

    fun notThisOne() { }
}
@fred.deschenes got it for me in #general
6 Views