当前位置:网站首页>Higher order functions in kotlin (first-class citizens)
Higher order functions in kotlin (first-class citizens)
2022-06-21 08:14:00 【Dialogue】
So let's talk about that Kotlin Higher order functions in
Kotlin Not a pure object-oriented language , Kotlin The function of is also a first-class citizen , So the function itself has its own The type of . Function types are like the data types described above , It can be used to define variables , It can also be used as a formal parameter class of a function type , It can also be used as the return value type of the function
- Use function types
Kotlin Each function of has a specific type , The function type is defined by the formal parameter list of the function 、 ·> And return value type . For example, the following functions :
fun foo(a : Int , name:String) ->String{
....
}List of formal parameters of the function 、-> And return value types are (Int , String) -> String, This is the type of the function .
fun bar(width : Double , height: Double) {
....
}List of formal parameters of the function 、 .> And return value types are (Double , Double)-> Unit or (Double, Double), This is Is the type of the function .
fun test() {
....
}List of formal parameters of the function 、 ·> And return value types are () ->Unit or (), This is the type of the function .
for example :
// Define a variable , The type of ( Int, Int) - > Int var myfun : (Int , Int) -> Int // Define a variable disk , The type of ( Stri mouth g) var test : (String)
After defining variables of function type , You can assign a function to this variable .
// Define a function that calculates the power
fun pow (ba$e: Int , exponent: Int) : Int {
var result = 1
for ( i in 1 . . exponent) {
result *= base
return result
// take pow The function is assigned to my fun , be my fun It can be taken as pow Use
myfun = ::pow
println(myfun(3 , 4)) // Output 81
// Define a function to calculate the area
fun area(width: Int , height : Int) : Int {
return width * height
// take area The function is assigned to my fun , be myfun It can be taken as area Use
myfun = : : area
println(myfun(3,4))// Output 12In turn pow()、 area() The function is assigned to myfun Variable ——— As long as it is assigned Function type and myfun The variable types of are consistent , You can assign the value successfully .
When accessing a function reference directly , Instead of calling a function , You need to add two colons before the function name , and And you can't add parentheses after a function Once you add parentheses , It becomes a call function , Instead of accessing function references . By using variables of function type , It can make myfun Point to different functions at different times , So that the program is more More flexibility . thus it can be seen , The advantage of using function types is to make the program more flexible . besides , Programs can also use function types as parameter types and return value types .
- Use function type as parameter type
Kotiin Support the use of function types as other types , Therefore, the shape of function type can be defined in the function ginseng
Example
// Define the formal parameters of the function type , among fn yes ( Int )→ Int Type parameters
fun map (data : Array<Int>, fn: (Int) -> Int) : Array<Int> {
var result = Array<Int>(data.size, { 0 })
// Traverse data Each element of the array , And use fn Function pair data[i ] Calculate
// Then take the result of the calculation as the element of the new array
for (i in data.indices) {
result[i] = fn(data[i])
}
return result
}
// Define a function that calculates the square
fun square (n : Int) : Int {
return n *n
// Define a function that calculates the cube
fun cube(n : Int) : Int {
return n * n * n
}
// Define a function that calculates factorials
fun factorial (n: Int ) : Int {
var result = 1
for (index in 2 .. n) {
result *= index
return result
}
fun main(args : Array<String>) {
var data= arrayOf (3 , 4 , 9 , 5 , 8)
println(" The original data ${data.contentToString()}")
// The following program code calls map () function 3 Time , Each call passes in a different function
println(" Calculate the square of array elements ")
println(map(data,::square).contentToString())
println(" Calculates the cube of an array element ")
println(map((data,::cube).contentToString())
println(" Calculate the factorial of array elements ")
println(map(data,::factorial).contentToString())
}Defined a map() function , The second parameter of the function is a formal parameter of a function type , This means This means that each time a function is called, a function can be dynamically passed in , As the actual incoming function changes , Can change dynamically map() Part of the calculation code in the function .
map() function 3 Time , 3 The following calls are passed in sequence square、 cub e 、 fac toria l Function as parameter , So every time I call map() The actual execution code of the function is different
- Use the function type as the return value type
Kotlin It also supports defining the return value of function types , In this way, other functions can be used as the return value of the function
Example
// Defined function , The return value type of this function l'l (Int)• Int
fun getMathFunc(type: String): (Int) -> Int {
// Define a local function that calculates the square
fun square(n: Int): Int {
return n * n
}
// Define a local function that calculates the cube
fun cude(n: Int): Int {
return n * n * n
}
// Define a local function that calculates factorial
fun factorial(n: Int): Int {
var result = 1
for (index in 2..n) {
result *= index
}
return result
}
when (type) {
// Return local function
"square" -> return ::square
"cube" -> return ::cude
else -> return ::factorial
}
}
fun main(args: Array<String>) {
// call getMathFunc (), The program returns a ( Int )→ Int Function of type
var mathFunc = getMathFunc("cube")// obtain cube function
println(mathFunc(5)) // Output 125
mathFunc = getMathFunc("square") // obtain j square function
println(mathFunc(5)) // Output 25
mathFunc = getMathFunc("other")// obtain factorial function
println(mathFunc(5)) // Output 120
}边栏推荐
- Three ways to solve cross domain problems
- 33 Jenkins modify plug-in source
- Introduction to testing - Software Test Model
- 2022-2028 global hydrogen engine industry research and trend analysis report
- An aunt's towel holds up the 100 billion market behind 400million Chinese women
- Global and Chinese market of Toro from 2022 to 2028: Research Report on technology, participants, trends, market size and share
- 使用Lua+Redis+OpenResty实现电商首页并发优化
- FD:文件描述符
- Markdown rule for writing articles
- showCTF 入门文件包含系列
猜你喜欢

Linux安装达梦数据库/DM8(附带客户端工具安装完整版)

2022-2028 global after sales spark plug industry research and trend analysis report

There was a GC failure in the online go service. I was in a hurry

為什呢代碼沒報錯但是數據庫裏邊的數據顯示不出來

测试入门——软件测试模型

为什呢代码没报错但是数据库里边的数据显示不出来

写文章的markdown规则

5 minutes to understand MySQL - row to column

图解 Google V8 # 15:隐藏类:如何在内存中快速查找对象属性?

Weekly update | showmebug officially launched Tencent conference audio and video
随机推荐
Three methods of bean instantiation
Illustration of Google V8 16: how does V8 improve function execution efficiency through inline caching?
[DB written interview 225] in Oracle, if the online redo log file is damaged, how to recover it?
Vision_ Transformer code exercise
图解 Google V8 # 15:隐藏类:如何在内存中快速查找对象属性?
Cluster hui dsm7 add suite source
1005 Spell It Right (20 分)(测试点3)
showCTF 入门文件包含系列
Classic topics of leetcode array (I)
Showctf web primer series
Represent each record in the dataframe as a dictionary
There was a GC failure in the online go service. I was in a hurry
php exec、 system 、shell_ Exec cannot be executed. There is no result. The result is nulld. Solution
Difference between function declaration and function expression
Upgrade Jenkins steps and problems encountered
為什呢代碼沒報錯但是數據庫裏邊的數據顯示不出來
Huasan IPSec
函数声明和函数表达式的区别
1004 Counting Leaves (30 分)
[actual combat] ACM players illustrate leetcode using stack to realize queue