获取高阶函数中函数参数的名称

Get name of function argument in higher-order function

Kotlin好像不支持获取局部函数等,请看下面的例子:

fun <T> MutableList<T>.filterOnCondition(condition: (T) -> Boolean): MutableList<T>
{ 
    // For the printline, trying to get the function name, 
    // which in this case is passedAsCondition
    println(condition.reflect()!!.instanceParameter!!.name)
}

fun passedAsCondition (number: Int, multipleOf : Int): Boolean
{
    return number % multipleOf == 0
}

numbers.filterOnCondition { passedAsCondition(it, 5) }

Kotlin returns 这个错误还没有被映射出来:

"kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Introspecting local functions, lambdas, anonymous functions and local variables is not yet fully supported in Kotlin reflection"

(https://github.com/JetBrains/kotlin/blob/master/core/reflection.jvm/src/kotlin/reflect/jvm/internal/EmptyContainerForLocal.kt#L41)

但是,这肯定可以通过 Java 完成,不是吗?

这是一个匿名函数,因此它的名称将是 <anonymous>:

val x: (Int) -> Boolean = { passedAsCondition(it, 5) }
println(x.reflect()?.name) //prints <anonymous>

当您有一个 lambda { passedAsCondition(it, 5) } 您希望反射在这里如何工作? passedAsCondition 是在 lambda 内部进行的一个简单调用,但是您在未命名的匿名 lambda 上调用 reflect,它没有名称。

普通函数可以与当然有名称的方法引用一起使用:

fun x(a: Int): Boolean {
    passedAsCondition(a, 5)
    return true
}
println(::x.name) //gives x

作为结果,利用适当的反射,以下工作:

fun main(args: Array<String>) {
    mutableListOf(1).filterOnCondition(::passedAsCondition)
}


fun <T> MutableList<T>.filterOnCondition(
    condition: KFunction2<@ParameterName(name = "number") Int, @ParameterName(name = "multipleOf") Int, Boolean>
) {
    println(condition.name)
}

fun passedAsCondition(number: Int, multipleOf: Int): Boolean = number % multipleOf == 0