kotlin 高阶函数_Kotlin:Lambda表达式和高阶函数

kotlin 高阶函数

Kotlin, as a statically typed programming language. This means the type of a variable is known at compile-time instead of at run-time.

Kotlin,作为一种静态类型的编程语言。 这意味着变量的类型在编译时(而不是运行时)是已知的。

Kotlin functions are the First-Class Function. This means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

Kotlin函数是一等函数。 这意味着该语言支持将函数作为参数传递给其他函数,将其作为其他函数的值返回,并将其分配给变量或存储在数据结构中。

First-class functions are a necessity for the functional programming style, in which the use of higher-order functions is a standard practice.

一流的函数是函数式编程风格的必要条件,其中使用高阶函数是一种标准做法。

Lambda表达式 (Lambda Expressions)

A lambda expression is always surrounded by curly braces, parameter declarations in the full syntactic form go inside curly braces and have optional type annotations, the body goes after an -> sign. If the inferred return type of the lambda is not Unit, the last (or possibly single) expression inside the lambda body is treated as the return value.

Lambda表达式始终被花括号包围,完整语法格式的参数声明位于花括号内并具有可选的类型注释,主体位于->符号之后。 如果推断的Lambda返回类型不是Unit,则将Lambda主体内的最后一个(或可能是单个)表达式视为返回值。

Lets say function which takes two int as the parameters, adds them, and returns as an int this we can achieve by two ways:

让我们说一个函数,它使用两个int作为参数,将它们相加,然后以int返回,这可以通过两种方式实现:

Without Lambda Expressions

没有 Lambda表达式

fun addTwoNumber (a: Int , b: Int) : Int {
return a+b
}val sumOfTwoNumber = addTwoNumber (2,3)

With Lambda Expressions

使用 Lambda表达式

val sumOfTwoNumber : (Int, Int) -> Int = { a: Int, b: Int -> a + b }

Lambda expressions and anonymous functions are ‘function literals’, i.e. functions that are not declared, but passed immediately as an expression. They provide us a compact way of writing code.

Lambda表达式和匿名函数是“函数文字”,即未声明但立即作为表达式传递的函数。 它们为我们提供了一种紧凑的代码编写方式。

高阶函数 (Higher Order Functions)

Higher-order function is a function that takes functions as parameters or returns a function. Passing lambda expression as a parameter to Higher-Order Functions.

高阶函数是 函数作为参数返回函数的函数 。 将lambda表达式作为参数传递给高阶函数。

Some of the basic higher-order functions are apply, with, let, also, and run etc. in Kotlin’s standard library.

一些基本的高阶函数在Kotlin的标准库中适用,一起使用,同时允许,也可以 运行

Example 1: Pass Lambda expression inside a higher order function as parameter

示例1:将 Lambda表达式作为参数传递给高阶函数

fun main(args: Array<String>) {
// Passing function body as a Lambda expressions
printStr({println("fun body passed as a Lambda expressions")})
}// Body of this method pass by calling function here i.e println()fun printStr(printingString: () -> Unit) {
printingString()
}

Example 2: Assign Lambda Expression to variable and pass variable as a parameter

示例2:将Lambda表达式分配给变量并将变量作为参数传递

// lambda expressionvar lambdaExpression = { println("Sample String to be print") }// higher-order functionfun higherOrderfunc( lambdaFuncParam: () -> Unit ) {
lambdaFuncParam() //invokes lambda expression}fun main(args: Array<String>) {
//invoke higher-order function
// passing lambda expression variable as parameter
higherOrderfunc (lambdaExpression) }

Explanation:

说明

Lambda Expression store into var variable name lambdaExpression which pass as a argument in higherOrderfunc() which accepting function as parameter lambdaFuncParam ( lambdaFuncParam is just the name for the parameter. It can be anything, We just need to use this when we execute the function ) and Unit represents that the function does not return any value.

将Lambda表达式存储到var变量名称lambdaExpression中 ,该变量将作为参数传递给HigherOrderfunc () 接受函数作为参数 lambdaFuncParam (lambdaFuncParam只是参数的名称。可以是任何东西,我们在执行函数时只需要使用它),并且Unit表示该函数不返回任何值。

Example 3: Function accept two parameter of Integer type and return Addition of both integers, that function pass as a parameter

示例3:函数接受两个Integer类型的参数并返回两个整数的加法,该函数作为参数传递

// regular function definitionfun addTwoNumbers(a: Int, b: Int): Int{
var sum = a + b
return sum
}// higher-order function definitionfun higherfunc(addfunction:(Int,Int)-> Int){
// invoke regular function using local name
var result = addfunction(3,6)
print("The Addition of a and b numbers is: $result")
}fun main(args: Array<String>) {
// invoke higher-order function
higherfunc(::addTwoNumbers)
}

Above three examples explain the case when functions as parameter. Now discuss another case i.e returning a function.

以上三个示例说明了用作参数的情况。 现在讨论另一种情况,即返回一个函数。

从高阶函数返回函数 (Returning a function from Higher-Order function)

While returning the function, we have to specify the parameter types and return type of regular function in the return type of the higher-order function.

在返回函数时,我们必须在高阶函数的返回类型中指定参数类型和常规函数的返回类型。

Lets understand which an example:

让我们看一个例子:

we define addition() function which accepts two integer parameters and its return type is also an integer. Then, we define the higher-order function having return type as a function.

我们定义了add()函数,该函数接受两个整数参数,并且其返回类型也是整数。 然后,我们将具有返回类型的高阶函数定义为一个函数。

// function declarationfun addition(a: Int, b: Int): Int{
return a*b
}//higher-order function declarationfun higherfunc() : ((Int,Int)-> Int){

// ::addition return addition() function reference
return ::addition }fun main(args: Array<String>) {

// invoke function and store the return function into a variable
val sumOfTwoNumber = higherfunc()

// invokes the addition() function by passing 2,4 arguments
val result = sumOfTwoNumber(2,4)
println("The addition of two numbers is: $result")
}

使用高阶函数的优点 (Advantages of Using Higher Order Functions)

  • Higher Order functions helps reduce the code redundancy by allowing the common code functionality to be passed as a function to another function.

    高阶函数通过允许将通用代码功能作为一个函数传递给另一个函数,有助于减少代码冗余。
  • Increases readability of the code.

    提高代码的可读性。

奖金!! (Bonus!!)

Higher order functions in JAVA

JAVA中的高阶函数

Before Java8, we used to pass a function to a function with the help of anonymous inner classes, but now we do that with the help of Lambdas.

在Java8之前,我们曾经借助于匿名内部类将函数传递给函数,但是现在我们借助Lambdas做到了。

Thanks for reading this article. Be sure to click 👏 below to applause this article if you found it helpful. It means a lot to me.

感谢您阅读本文。 如果发现有帮助,请确保单击下面的to以赞扬本文。 它对我意义重大。

其他有用的链接 (Other Useful Links)

翻译自: https://medium.com/swlh/kotlin-lambda-expressions-and-higher-order-functions-80029f5b9941

kotlin 高阶函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值