当前位置:网站首页>[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
- Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents
- FPN网络详解
- EndeavourOS移动硬盘安装
- Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)
- 德国iF多项大奖加冕,这副耳机有多强?音珀GTW 270 Hybrid深度评测
- Vscode find and replace the data of all files in a folder
- 独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作
- 数据库系统原理与应用教程(005)—— yum 离线安装 MySQL5.7(Linux 环境)
- In the past six months, it has been invested by five "giants", and this intelligent driving "dark horse" is sought after by capital
猜你喜欢
今天14:00 | 港大、北航、耶鲁、清华、加大等15位ICLR一作讲者精彩继续!
Vscode find and replace the data of all files in a folder
VMware 虛擬機啟動時出現故障:VMware Workstation 與 Hyper-v 不兼容...
數據庫系統原理與應用教程(006)—— 編譯安裝 MySQL5.7(Linux 環境)
[SQL statement] Why do you select two Shanghai and query different counts here? I want it to become a Shanghai, and count only displays a sum
Mlperf training v2.0 list released, with the same GPU configuration, the performance of Baidu PaddlePaddle ranks first in the world
China's intelligent transportation construction from the perspective of "one hour life circle" in Dawan District
How to write good code - Defensive Programming Guide
StoneDB 为国产数据库添砖加瓦,基于 MySQL 的一体化实时 HTAP 数据库正式开源!
VMware virtual machine failed during startup: VMware Workstation is incompatible with hyper-v
随机推荐
Go 语言怎么优化重复的 if err != nil 样板代码?
IM即时通讯开发实现心跳保活遇到的问题
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents
Ring iron pronunciation, dynamic and noiseless, strong and brilliant, magic wave hifiair Bluetooth headset evaluation
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...
Talking from mlperf: how to lead the next wave of AI accelerator
Advantages, values and risks of chain games compared with traditional games
Stegano in the world of attack and defense
How long will it take to achieve digital immortality? Metacosmic holographic human avatar 8i
Problems encountered in IM instant messaging development to maintain heartbeat
红队第10篇:coldfusion反序列化过waf改exp拿靶标的艰难过程
Virtual serial port simulator and serial port debugging assistant tutorial "suggestions collection"
普通二本,去过阿里外包,到现在年薪40W+的高级测试工程师,我的两年转行心酸经历...
程序员职业生涯真的很短吗?
SQLServer查询: a.id与b.id相同时,a.id对应的a.p在b.id对应的b.p里找不到的话,就显示出这个a.id和a.p
Research on multi model architecture of ads computing power chip
Learn selenium to simulate mouse operation, and you can be lazy a little bit
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?