[英]Get name of function argument in higher-order function
It seems that Kotlin does not support getting local functions etc. Please see the example below: 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 this error as it has not been mapped out yet: Kotlin 返回此错误,因为它还没有被映射出来:
"kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Introspecting local functions, lambdas, anonymous functions and local variables is not yet fully supported in Kotlin reflection" “kotlin.reflect.jvm.internal.KotlinReflectionInternalError:Kotlin 反射尚未完全支持内省局部函数、lambda、匿名函数和局部变量”
( https://github.com/JetBrains/kotlin/blob/master/core/reflection.jvm/src/kotlin/reflect/jvm/internal/EmptyContainerForLocal.kt#L41 ) ( https://github.com/JetBrains/kotlin/blob/master/core/reflection.jvm/src/kotlin/reflect/jvm/internal/EmptyContainerForLocal.kt#L41 )
BUT, surely this is possible to do via Java, is it not?但是,这肯定可以通过 Java 来实现,不是吗?
It's an anonymous function, thus it's name will be <anonymous>
:这是一个匿名函数,因此它的名称将是<anonymous>
:
val x: (Int) -> Boolean = { passedAsCondition(it, 5) }
println(x.reflect()?.name) //prints <anonymous>
When you have a lambda { passedAsCondition(it, 5) }
how would you expect the reflection to work here?当您有一个 lambda { passedAsCondition(it, 5) }
,您希望反射如何在这里工作? passedAsCondition
is a simple call made inside the lambda, but you're invoking the reflect
on an unnamed, anonymous, lambda, which does not have a name. passedAsCondition
是在 lambda 内部进行的一个简单调用,但是您正在对没有名称的未命名、匿名的 lambda 调用reflect
。
Ordinary functions can be used with method references which of course do have a name:普通函数可以与方法引用一起使用,这些方法引用当然有名称:
fun x(a: Int): Boolean {
passedAsCondition(a, 5)
return true
}
println(::x.name) //gives x
As a result , making use of proper reflection, the following works:因此,利用适当的反射,以下工作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.