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)


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) {

    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) {

    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) {
    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) {
    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) {
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) {
    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) {
//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(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.

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

Download Kotlin Higher Order Functions Lambda Expressions Project 下载Kotlin高阶函数Lambda表达式项目

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

kotlin 高阶函数

你可能感兴趣的:(字符串,列表,python,java,lambda)