我是函数编程语言的新手,我刚刚经历了一个名为高阶函数的新概念。
我见过一些高阶函数,如filter()
、map()
、flatMap()
、take()
、drop()
和zip()
。我只能获得这个高阶函数的详细信息。
My question is:
这些是 kotlin 中唯一可用的高阶函数,或者还有更多高阶函数可用。
我不确定,我们是否也可以创建供个人使用的高阶函数?
提前谢谢。
是的,Kotlin 中还有更多高阶函数,例如apply
、also
、lazy
、let
、onSuccess
、recover
、recoverCatching
、repeat
、run
、runCatching
、suspend
、with
、use
。 浏览使用其他函数作为值的函数的参考文档,例如 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/、https://kotlinlang.org/docs/tutorials/kotlin-for-py/functional-programming.html#nice-utility-functions。
是的,用户可以定义高阶函数。 有关如何定义和使用高阶函数的信息,请参阅 https://kotlinlang.org/docs/reference/lambdas.html。
正如在与 Java 页面的比较第 4 点中提到的,Kotlin 具有适当的函数类型,而不是 Java 的 SAM 转换。
我的意思是,如果你想接受一个函数或某种可以在Java 中调用的代码,你需要一个外部接口,只有 1 个方法,它知道返回类型和参数签名。
例如在Java中:
// You can't create this unless you create FuncInterface defining its parameter and return type
MyFuncInterface a = (s) -> System.out.println(s);
interface MyFuncInterface {
public void myMethod(String s);
}
// now call a like
a.myMethod("Hello World"); // will print: Hello World
a.myMethod("Test"); // will print: Test
虽然在 kotlin 中不是这种情况,但您可以创建 lambda,而无需在此处创建接口。
例如,Kotlin 中的相同代码可以转换为:
val a: (String) -> Unit = { println(it) }
// or like this: val a: (String) -> Unit = { s -> println(s) }
// call like this
a("Hello World") // will print: Hello World
a("Test") // will print: Test
由于 Kotlin 具有适当的函数类型,因此您可以使函数接受函数类型或返回函数类型,然后称为高阶函数。
概念类似:
// This is a higher order functon, takes a callable function `f`
fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
// this types are useful as callbacks, instead of taking nums and passing them
// you can compute heavy tasks and when they complete call f with the result
return f(num1, num2)
}
// lambda can be put outside the parentheses if it is last parameter
// also is another higher order function which calls the lambda passed with the object it was called on as a parameter
operatesFOn(3, 4) { a, b -> a + b }.also { println(it) } // prints: 7
operatesFOn(5, 7) { a, b -> a * b }.also { println(it) } // prints: 35
还有一些其他很酷的修饰符以及用于高阶函数(如内联修饰符(的修饰符。
inline fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
return f(num1, num2)
}
上面的方法类似,但lambda 将在编译时内联到调用站点,以减少调用堆栈,从而提高性能。 如文档中也提到:
使用高阶函数会施加某些运行时惩罚:每个函数都是一个对象,它捕获一个闭包,即在函数主体中访问的那些变量。内存分配(函数对象和类(和虚拟调用会引入运行时开销。