Hi, how to obtain all functions that have a functi...
# announcements
l
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
f
Do you have an example what you want to look for?
l
I have a lot of function overloads, such as
Copy code
fun foo<A>(fn: (A) -> Unit) {}
fun foo<A. B>(fn: (A, B) -> Unit) {}
fun foo <A, B, C>(fn: (A, B, C) -> Unit) {}
...
I want to find all the functions that contain this kind of
fn
So I wanted to filter for
Copy code
Foo::class.filter { function -> function.parameters.any { /* it is of function type */  }
The original problem is I want to write a test for all these functions, but don't want to write 22 tests
As their behavior is pretty much the same
f
this seems to work :
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() { }
}
since this is for unit tests it should be good enough, but I'm not sure enough about all edge cases with this (ex: I don't think it would catch java functional interfaces and stuff like that)
and the
Function
is kotlin`s
Function
in the kotlin package, not java.lang.Function btw
l
Oh, wow. That's about it!
It did work indeed.
f
👍
l
amazing, @fred.deschenes. Thanks!
f
no problem!