我目前正在学习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"块中变量的类型,所以我try 在这里做同样的事情.判断变量是否为函数类型.
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 Expect",我猜是因为Fun本身不是一种类型.
我试着搜索"Kotlin判断变量是否为函数",但我在哪里找到的都是关于如何判断原语或类的指南,甚至没有提到函数.