首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Kotlin高阶函数

Kotlin高阶函数
EN

Stack Overflow用户
提问于 2020-05-27 04:01:41
回答 2查看 1.1K关注 0票数 0

我是一个新的函数编程语言,我刚刚经历了一个叫做高阶函数的新概念。

我见过一些高阶函数,如filter()map()flatMap()take()drop()zip().我只能得到这个高阶函数的细节。

My question is:,这些是kotlin中唯一可用的高阶函数,或者也有更多的高阶函数可用。

我不确定,我们是否也能为个人使用创造更高层次的功能?

提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-27 04:55:17

正如与Java的比较页面的第4点所提到的,Kotlin有适当的函数类型,而不是Java转换。

我的意思是,如果您想接受一个函数或某种类型的代码,那么您可以在函数内部调用它,您的需要一个外部接口,它有一个确切的方法,它知道返回类型和参数签名。

例如,在Java中:

代码语言:javascript
复制
// 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中的相同代码可以转换为:

代码语言:javascript
复制
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有适当的函数类型,所以可以使函数接受函数类型或返回函数类型,然后称为高阶函数

概念相似:

代码语言:javascript
复制
// 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

对于高阶函数,比如内联修饰符,还有其他一些很酷的修饰符。

代码语言:javascript
复制
inline fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
    return f(num1, num2)
}

上面的工作方式类似,但是lambda将在编译时被内联在调用站点上,以减少调用堆栈,从而提高性能。正如文档中所提到的那样:

使用高阶函数会造成一定的运行时惩罚:每个函数都是一个对象,它捕获一个闭包,即函数正文中访问的那些变量。内存分配(包括函数对象和类)和虚拟调用都会带来运行时开销。

票数 2
EN

Stack Overflow用户

发布于 2020-05-27 05:22:49

是的,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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62035218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档