当前位置:网站首页>[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 !
边栏推荐
- P2592 [ZJOI2008]生日聚会(dp)
- Défaillance lors du démarrage de la machine virtuelle VMware: le poste de travail VMware n'est pas compatible avec hyper - V...
- 怎麼用MySQL語言進行行列裝置?
- How to use phpipam to manage IP addresses and subnets
- 德国iF多项大奖加冕,这副耳机有多强?音珀GTW 270 Hybrid深度评测
- 全面看待企业数字化转型的价值
- Zabbix2.2 monitoring system and application log monitoring alarm
- 圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
- How to write good code - Defensive Programming Guide
- 今天14:00 | 港大、北航、耶鲁、清华、加大等15位ICLR一作讲者精彩继续!
猜你喜欢
Problèmes rencontrés dans le développement de la GI pour maintenir le rythme cardiaque en vie
How to restore the system of Sony laptop
How to use MySQL language for row and column devices?
【Hot100】20. Valid parentheses
China's intelligent transportation construction from the perspective of "one hour life circle" in Dawan District
Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents
【直播预约】数据库OBCP认证全面升级公开课
Rhcsa Road
Ring iron pronunciation, dynamic and noiseless, strong and brilliant, magic wave hifiair Bluetooth headset evaluation
投稿开奖丨轻量应用服务器征文活动(5月)奖励公布
随机推荐
vim用户自动命令示例
MLPerf Training v2.0 榜单发布,在同等GPU配置下百度飞桨性能世界第一
毕业后5年,我成为了年薪30w+的测试开发工程师
怎麼用MySQL語言進行行列裝置?
Why is the pkg/errors tripartite library more recommended for go language error handling?
IM即時通訊開發實現心跳保活遇到的問題
Origin2018 installation and use (sorting)
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
The picgo shortcut is amazing. This person thinks exactly the same as me
模板引擎Velocity 基础
OJ questions related to complexity (leetcode, C language, complexity, vanishing numbers, rotating array)
Golang爬虫框架初探
部门来了个拿25k出来的00后测试卷王,老油条表示真干不过,已被...
Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents
PostgreSQL 存储结构浅析
Comment utiliser le langage MySQL pour les appareils de ligne et de ligne?
Défaillance lors du démarrage de la machine virtuelle VMware: le poste de travail VMware n'est pas compatible avec hyper - V...
博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”
广东用电量大跌,说明高新技术产业替代高能耗产业已取得初步成果
Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist