当前位置:网站首页>[kotlin] Introduction to higher-order functions
[kotlin] Introduction to higher-order functions
2022-07-01 16:38:00 【Programmer Xiao He SS】
What is a higher-order function
A function that takes a function as an argument or returns a value , Called higher order function .
Define higher-order functions
action It's a function of higher order ,(Int) -> Int Indicates the type of the function ,(Int) Indicates that the input parameter type of the function is Int, hinder Int Indicates the return type of the function .
private fun init() {
val action: ((Int) -> Int) = {// Function to add 100 operation
it + 100
}
}
Function as parameter
The following code ,init Function call doSomething function , take Int type 0 as well as action Function is introduced to doSomething.doSomething The function first aligns the parameters 0 add 200 operation , Then we call the higher-order function. action( add 100 operation ), Final print results actionResult. Is it a bit of a strategic design pattern ? Yes , It can be used to implement the strategy design pattern .
private fun init() {
val action: ((Int) -> Int) = {// Function to add 100 operation
it + 100
}
doSomething(0, action)// take 0 as well as action Pass to doSomething
}
private fun doSomething(d: Int, action: (Int) -> Int) {
val data = d + 200// First pair d add 200 operation
val actionResult = action(data)// Will add 200 The result is passed to action, The results are stored in actionResult in
Log.e("test", "actionResult=${actionResult}")// Print the results
}
Function as return value
The following code , Depending on the type type, Return the corresponding action, Then the parameters 0 Carry out operations , Final print results .
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val action = init(" programme 1")
// Get the corresponding action, Pass in the parameter 0 Carry out operations
val result = action?.invoke(0)
// Print the results
Log.e("test", "result=${result}")
}
private fun init(type: String): ((Int) -> Int)? {
val action1: ((Int) -> Int) = {// Add 100 operation
it + 100
}
val action2: ((Int) -> Int) = {// Add 200 operation
it + 200
}
// According to the type type, Return the corresponding action
return when (type) {
" programme 1" -> action1
" programme 2" -> action2
else -> null
}
}
lamdba expression
It's also a higher-order function , It's just that the function is anonymous . The function of the following code is the same as the above , Just for amdba Expressions replace definitions action function .
private fun init() {
doSomething(0) { // take 0 as well as lambda The expression is passed to doSomething
it + 100// add 100 operation , And back to
}
}
private fun doSomething(d: Int, action: (Int) -> Unit) {
val data = d + 200// First pair d add 200 operation
val actionResult = action(data)// Will add 200 The result is passed to action, The results are stored in actionResult in
Log.e("test", "actionResult=${actionResult}")// Print the results
}
What is the essence of higher-order functions ?
Decompile the first example
private static final void init() {
Function1 action = new Function1() {//1
@Override
public Object invoke(Object o) {
return ((Integer)o).intValue() + 100;//2
}
};
doSomething(0, action);
}
private static final void doSomething(int d, Function1 action) {//3
int data = d + 200;
int actionResult = ((Number)action.invoke(data)).intValue();
Log.e("test", "actionResult=" + actionResult);
}
- notes 1:Kotlin The compiler converts higher-order functions into Function1;
- notes 2: Implementation of corresponding higher-order function ;
- notes 3: Call higher-order functions , In fact, the trigger is invoke function ;
There is something wrong with the above analysis , Please point out , learn from each other , Thank you !
边栏推荐
- [daily news]what happened to the corresponding author of latex
- Research on multi model architecture of ads computing power chip
- 芯片供应转向过剩,中国芯片日产增加至10亿,国外芯片将更难受
- IM即時通訊開發實現心跳保活遇到的問題
- Ring iron pronunciation, dynamic and noiseless, strong and brilliant, magic wave hifiair Bluetooth headset evaluation
- Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
- Is the programmer's career really short?
- 复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
- Five years after graduation, I became a test development engineer with an annual salary of 30w+
- 【SQL语句】请问这边为什么select出了两个上海,查询出了不同的count我想让他变成一个上海,count只显示一个总和
猜你喜欢

Pico, do you want to save or bring consumer VR?

The supply of chips has turned to excess, and the daily output of Chinese chips has increased to 1billion, which will make it more difficult for foreign chips

Défaillance lors du démarrage de la machine virtuelle VMware: le poste de travail VMware n'est pas compatible avec hyper - V...

OJ questions related to complexity (leetcode, C language, complexity, vanishing numbers, rotating array)

Rhcsa Road

The picgo shortcut is amazing. This person thinks exactly the same as me

Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist

What is the digital transformation of manufacturing industry

【SQL语句】请问这边为什么select出了两个上海,查询出了不同的count我想让他变成一个上海,count只显示一个总和

VMware 虚拟机启动时出现故障:VMware Workstation 与 Hyper-v 不兼容...
随机推荐
Apple's self-developed baseband chip failed again, which shows Huawei Hisilicon's technological leadership
Buuctf gold III
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”
How to solve the problem that the battery icon of notebook computer does not display
Virtual serial port simulator and serial port debugging assistant tutorial "suggestions collection"
VMware 虛擬機啟動時出現故障:VMware Workstation 與 Hyper-v 不兼容...
UML旅游管理系统「建议收藏」
Huawei issued hcsp-solution-5g security talent certification to help build 5g security talent ecosystem
PR basic clip operation / video export operation
Guide for high-end programmers to fish at work
[JetsonNano] [教程] [入门系列] [三] 搭建TensorFlow环境
Leetcode 77 combination -- backtracking method
Principle of SSM framework
Stegano in the world of attack and defense
德国iF多项大奖加冕,这副耳机有多强?音珀GTW 270 Hybrid深度评测
Rhcsa Road
SQLServer查询: a.id与b.id相同时,a.id对应的a.p在b.id对应的b.p里找不到的话,就显示出这个a.id和a.p
IM即时通讯开发万人群聊消息投递方案
Building blocks for domestic databases, stonedb integrated real-time HTAP database is officially open source!