我是函数编程语言的新手,刚经历了一个称为高阶函数的新概念。
我已经看到一些高阶函数,例如filter()
,map()
,flatMap()
,take()
,drop()
和zip()
。我只能获得此高阶函数的详细信息。
My question is:
这些是kotlin中唯一可用的高阶函数,或者还有更多的高阶函数可用。
我不确定,我们是否也可以创建供个人使用的高阶函数?
先谢谢了。
答案 0 :(得分:3)
是的,Kotlin中还有更多的高阶函数,例如apply
,also
,lazy
,let
,onSuccess
,{{ 1}},recover
,recoverCatching
,repeat
,run
,runCatching
,suspend
,with
。浏览参考文档,了解将其他功能用作值的功能,例如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。
答案 1 :(得分:2)
如Comparison to Java页第4点所述,与Java的SAM转换相反,Kotlin具有适当的函数类型。
我的意思是,如果您想接受一个函数或Java中的某种代码 ,您可以在一个函数内部调用,则需要一个外部接口,该接口应具有仅一种方法知道返回类型和参数签名。
例如在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具有适当的函数类型,因此您可以使函数接受一个函数类型或返回一个函数类型,然后将其称为Higher-Order Function。
概念相似:
// 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修饰符。
inline fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
return f(num1, num2)
}
以上代码的工作原理类似,但是 lambda会在编译时内联到调用站点,以减少调用堆栈,从而提高性能。如docs所述:
使用高阶函数会产生某些运行时惩罚:每个函数都是一个对象,并且它捕获一个闭包,即在函数主体中访问的那些变量。内存分配(用于函数对象和类)和虚拟调用都会导致运行时开销。