gpt4 book ai didi

kotlin - 检查 Kotlin 变量是否为函数

转载 作者:行者123 更新时间:2023-12-05 01:49:11 29 4
gpt4 key购买 nike

我目前正在学习 Kotlin 并且正在研究 By Example Guide .在函数/高阶函数一章中,它解释了函数本身如何通过这个例子返回函数:

fun operation(): (Int) -> Int {                                    
return ::square
}

fun square(x: Int) = x * x

fun main() {
val func = operation()
println(func(2))
}

因为我之前已经学会了在“when” block 中检查变量的类型,所以我在这里尝试做同样的事情。检查变量是否为函数类型。

fun operation(): (Int) -> Int {                                   
return ::square
}

fun square(x: Int) = x * x

fun main() {
val func = operation()
when (func){
is fun -> println(func(2))
else -> println("Not a function")
}
}

但这会引发错误“Type expected”,我猜是因为 fun 本身不是一种类型。

我尝试搜索“kotlin 检查变量是否为函数”之类的内容,但我只能找到有关如何检查基元或类的指南,甚至没有提到函数。

最佳答案

假设您对 func 一无所知. ( func 属于 Any 类型)您可以通过以下操作轻松检查它是否是一个函数:

if (func is Function<*>) {
...
}

或者类似地使用is Function<*>when分支机构。

但是,这并没有告诉您参数的数量或类型,或者返回类型。由于您想使用 Int 调用该函数在这里,重要的是您还要检查该函数是否只有一个类型为 Int 的参数。 .您可以在 Function 之后添加一个数字检查特定数量的参数,

if (func is Function1<*, *>) {
...
}

但这就是简单的事情停止的地方。

检查参数类型非常困难。你不能只这样做:

if (func is Function1<Int, Int>) {
...
}

因为泛型是 erased ,运行时无法区分 Function1<Int, Int>和一个 Function1<Foo, Bar> ,因此您无法使用 is 检查特定类型参数.

不幸的是,我能想到的唯一方法是反射(reflection)。

// JVM only
if (func is Function1<*, *> &&
(func as? KFunction<*> ?: func.reflect())?.parameters?.singleOrNull()?.type == typeOf<Int>()) {
// this is an unchecked cast, which means the runtime won't check it
// but it is fine, because the code above checked it
println((func as Function1<Int, *>)(2))
}

operation可以返回 KFunction , 就像你的 ::square , 或 lambda。如果它返回一个 lambda,则 reflect 实验性 API(您需要 @OptIn(ExperimentalReflectionOnLambdas::class))用于将其转换为 KFunction .

在我们有一个KFunction之后,我们可以检查它的单个参数(如果它有一个)并检查它是否是 Int .

因此检查特定类型的函数非常痛苦。如果您发现自己需要这样做,我建议您更改设计以避免这样做。

关于kotlin - 检查 Kotlin 变量是否为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74400339/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com