kotlin 高阶函数_Kotlin Lambda表达式,高阶函数

kotlin 高阶函数

In this tutorial, we’ll be looking into kotlin higher-order functions and lambda expressions in detail. At the same time, we’ll explore function references, anonymous functions, and closures too.

在本教程中,我们将详细研究kotlin高阶函数和lambda表达式。 同时,我们还将探索函数引用,匿名函数和闭包。

Kotlin高阶函数 (Kotlin Higher-Order Functions)

Kotlin supports functional programming. High order functions have the ability to pass a function as an argument or use it as the return value. Let’s see this through examples.

Kotlin支持功能编程。 高阶函数可以将函数作为参数传递或将其用作返回值。 让我们通过示例来看一下。

函数类型和引用 (Function Types and References)

Functions in Kotlin are types.
()->String is a type that takes no parameters and returns a string.
(String)->String is a type that takes a string argument and returns a string argument.

Kotlin中的函数是类型。
()->String是一种不带参数且返回字符串的类型。
(String)->String是一种接受字符串参数并返回字符串参数的类型。

Kotlin Lambda表达式 (Kotlin Lambda Expressions)

kotlin lambda expression

Lambda Expressions are function literals that help us in writing a function in a short way. They provide us a compact way of writing code. Let’s define a lambda expression to see how functions act as types.


Lambda表达式是函数文字,可以帮助我们以简短的方式编写函数。 它们为我们提供了一种紧凑的代码编写方式。 让我们定义一个lambda表达式以查看函数如何充当类型。

fun main(args: Array<String>) {

    var lambdaFunction :(String)->Unit  = {s:String -> println(s)}
    lambdaFunction("Kotlin Lambda Functions")

    //or
    lambdaFunction =  {println(it)}
    lambdaFunction("Kotlin Lambda Functions Concise")

    val noArgFunction : () -> Unit ={ println("Another function")}
    noArgFunction()

}

//Following is printed on the console.
//Kotlin Lambda Functions
//Kotlin Lambda Functions Concise
//Another function

lambdaFunction property has a function as its type. The right-hand side is where the function is declared.

lambdaFunction属性具有一个函数作为其类型。 右侧是函数的声明位置。

it is used to access parameter values in the body of the lambda expression.

it用于访问lambda表达式主体中的参数值。

We can pass a function as a parameter inside another function too using references as shown below.

我们也可以使用引用将函数作为参数传递给另一个函数,如下所示。

Such functions are known as High Order Functions.

这样的函数称为高阶函数

fun main(args: Array<String>) {

    var printFunction: (String) -> Unit = { println(it) }
    functionReferencesExample("JournalDev.com", printFunction)

}

fun functionReferencesExample(str: String, expression: (String) -> Unit) {
    print("Welcome To Kotlin Series @")
    expression(str)
}

To pass a function as an argument inside another function we need to use the notation ::. Following code snippet demonstrates an example on the same.

要将函数作为参数传递给另一个函数,我们需要使用符号:: 。 下面的代码片段在同一示例上演示了一个示例。

fun main(args: Array<String>) {
    functionReferencesExample("JournalDev.com", ::printFunction)
}

fun functionReferencesExample(str: String, expression: (String) -> Unit) {
    print("Welcome To Kotlin Series @")
    expression(str)
}

fun printFunction(str: String) {
    println(str)
}

Note: We’ll look at High order functions and lambda expressions in detail in a later tutorial.

注意 :我们将在以后的教程中详细介绍高阶函数和lambda表达式。

高阶函数中的Lambda表达式 (Lambda Expressions inside Higher Order Functions)

A Lambda expression can be passed inside a higher order function parameter as shown below.

Lambda表达式可以在高阶函数参数中传递,如下所示。

fun main(args: Array<String>) {
    printMe({ println("Lambda Inside a function")}) //prints Lambda Inside a function
}

fun printMe(string1: () -> Unit) {
    string1()
}

The lambda expression as a parameter runs as a function inside another function.

lambda表达式作为参数在另一个函数中作为函数运行。

Another example demonstrates using lambda expressions inside print function.

另一个示例演示了在print函数内部使用lambda表达式。

fun main(args: Array<String>) {
println("Let's invoke a lambda function ${returnMe { "return Me " + "function"  }} here")
}

fun returnMe(string: ()->String) : String
{
    return string()
}

//Prints
//Let's invoke a lambda function return Me function here

类型别名 (Type Aliases)

Typealiases provide an alternative name for a type.
Instead of typing the function type every time when defining a property, we can use typealias as shown below.

Typealiases为类型提供了备用名称。
不必在定义属性时每次都键入函数类型,而是可以使用如下所示的类型typealias

fun main(args: Array<String>) {
    var printFunction: MyFirstAlias = { println(it) }
}

typealias MyFirstAlias =  (String)->Unit

typeAlias Username = String

This definitely enhances the readability of the code.

这无疑提高了代码的可读性。

异常函数 (Annoymous Functions)

We’ve seen that lambda expressions can’t explicitly specify a return type as illustrated below.

我们已经看到,lambda表达式无法显式指定返回类型,如下所示。

var sum = { a: Int, b: Int -> a + b }
var result = sum(2,3) //result is an int 5

In order to set the return types explicitly, we can use Annoymous functions.
An annoymous function doesn’t require a name.

为了显式设置返回类型,我们可以使用Annoymous函数。
异常函数不需要名称。

fun main(args: Array<String>) {
//Defining
val annoSum = fun(x: Int, y: Int): Int = x + y
//Invoking
print(annoSum(2,3)) //5
}

If the parameter/return type of the annoymous function isn’t defined, it can be inferred just like normal functions.

如果未定义匿名函数的参数/返回类型,则可以像普通函数一样进行推断。

Let’s use Anonymous functions inside standard library high order functions.

让我们在标准库高阶函数中使用匿名函数。

var myList = listOf<Int>(1,2,5,7,6,10)

    myList = myList.filter(fun(item) = (item%2 ==0) )
    println(myList)

filter is a higher order function that checks the given condition over each of the list items.
In the above code, it checks for odd/even over each list integer element.

filter是一个高阶函数,用于检查每个列表项上的给定条件。
在上面的代码中,它检查每个列表整数元素的奇/偶数。

Note: There are plenty of standard library functions. We’ll look at them and there use cases in a later tutorial.

注意:有很多标准库函数。 我们将在以后的教程中研究它们以及用例。

Kotlin封盖 (Kotlin Closures)

Closures are functions that can access and modify properties defined outside the scope of the function.
The following closure function is a high order function that calculates the sum of all elements of the list and updates a property defined outside the closure.

闭包是可以访问和修改在函数范围之外定义的属性的函数。
下面的闭包函数是一个高阶函数,它计算列表中所有元素的总和并更新在闭包外部定义的属性。

var res = 0
myList = listOf(1,2,3,4,5,6,7,8,9,10)
myList.forEach { res+=it }
println(res) //prints 55

This brings an end to this tutorial. We’ll be looking at the standard library higher-order functions in a later tutorial. You can download the sample code of the above tutorial from the link below.

本教程到此结束。 在后面的教程中,我们将研究标准库的高阶函数。 您可以从下面的链接下载上述教程的示例代码。

翻译自: https://www.journaldev.com/18835/kotlin-lambda-higher-order-functions

kotlin 高阶函数

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Kotlin中,高阶函数有多种用法。除了使用Lambda表达式来传递函数参数外,还可以使用匿名函数和成员引用等方式。 Lambda表达式是最基本的高阶函数用法,通过Lambda表达式可以直接在调用高阶函数时指定传入的参数。比如在调用num1AndNum2()函数时,可以通过Lambda表达式指定传入的两个整数参数进行求和。 除了Lambda表达式Kotlin还支持匿名函数的语法。匿名函数的写法更类似于常规的函数定义,可以有函数名和参数列表,而Lambda表达式则是简化的匿名函数写法。匿名函数适用于需要在函数体内使用return语句来提前返回结果的情况。 此外,Kotlin的编译器还会将高阶函数的语法转换成Java支持的语法结构。换句话说,Kotlin高阶函数在底层实现上会被转换成Java代码。具体来说,Kotlin高阶函数会被转换成接收函数对象作为参数的Java方法。 总结来说,Kotlin高阶函数用法包括Lambda表达式、匿名函数和成员引用等。这些用法使得我们可以更灵活地编写代码,并将高阶函数的语法转换成Java支持的形式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Kotlin 高阶函数](https://blog.csdn.net/weixin_56504344/article/details/124973388)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Kotlin高阶函数](https://blog.csdn.net/ChenYiRan123456/article/details/127983199)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值