Kotlin高阶函数

ghg1uchk  于 2023-11-21  发布在  Kotlin
关注(0)|答案(2)|浏览(360)

我是函数式编程语言的新手,我刚刚接触到一个新概念,叫做高阶函数。
我见过高阶函数,如filter()map()flatMap()take()drop()zip()。我只在Kotlin文档中见过这些高阶函数。
My question is:这些是Kotlin中唯一可用的高阶函数,或者还有更多高阶函数可用。
我不确定,我们是否也可以创建供个人使用的高阶函数?
先谢了。

pvabu6sv

pvabu6sv1#

是的,Kotlin中有更多高阶函数,例如applyalsolazyletonSuccessrecoverrecoverCatchingrepeatrunrunCatchingsuspendwithuse。浏览参考文档,了解使用其他函数作为值的函数,例如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

7vhp5slm

7vhp5slm2#

正如Comparison to Java页面的第4点所提到的,Kotlin有适当的函数类型,而不是Java的SAM转换。
我的意思是,如果你想接受一个函数或某种Java代码**,你可以在函数内部调用,你需要一个外部接口,只有一个方法知道返回类型和参数签名
例如在Java中:

  1. // You can't create this unless you create FuncInterface defining its parameter and return type
  2. MyFuncInterface a = (s) -> System.out.println(s);
  3. interface MyFuncInterface {
  4. public void myMethod(String s);
  5. }
  6. // now call a like
  7. a.myMethod("Hello World"); // will print: Hello World
  8. a.myMethod("Test"); // will print: Test

字符串
虽然在Kotlin中并非如此,但您可以在这里创建lambda而无需创建接口。
例如,Kotlin中的相同代码可以转换为:

  1. val a: (String) -> Unit = { println(it) }
  2. // or like this: val a: (String) -> Unit = { s -> println(s) }
  3. // call like this
  4. a("Hello World") // will print: Hello World
  5. a("Test") // will print: Test


由于Kotlin有适当的函数类型,你可以让一个函数接受一个函数类型或返回一个函数类型,然后将其称为高阶函数。
概念相似:

  1. // This is a higher order functon, takes a callable function `f`
  2. fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
  3. // this types are useful as callbacks, instead of taking nums and passing them
  4. // you can compute heavy tasks and when they complete call f with the result
  5. return f(num1, num2)
  6. }
  7. // lambda can be put outside the parentheses if it is last parameter
  8. // also is another higher order function which calls the lambda passed with the object it was called on as a parameter
  9. operatesFOn(3, 4) { a, b -> a + b }.also { println(it) } // prints: 7
  10. operatesFOn(5, 7) { a, b -> a * b }.also { println(it) } // prints: 35


还有一些其他很酷的修改器,以及高阶函数,如inline修改器。

  1. inline fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
  2. return f(num1, num2)
  3. }


上面的一个将工作类似,但lambda将改为在编译时内联在调用站点,以减少调用堆栈提高性能。正如在docs中提到的那样:
使用高阶函数会带来一定的运行时损失:每个函数都是一个对象,它捕获一个闭包,即在函数体中访问的那些变量。内存分配(函数对象和类)和虚调用会引入运行时开销。

展开查看全部

相关问题