当前位置:网站首页>[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 !
边栏推荐
- Red team Chapter 8: blind guess the difficult utilization process of the package to upload vulnerabilities
- 红队第10篇:coldfusion反序列化过waf改exp拿靶标的艰难过程
- 瑞典公布决定排除华为5G设备,但是华为已成功找到新出路
- How to optimize repeated if err in go language= Nil template code?
- Germany if was crowned with many awards. How strong is this pair of headphones? In depth evaluation of yinpo GTW 270 hybrid
- 用手机在同花顺上开户靠谱吗?这样有没有什么安全隐患
- [jetsonnano] [tutorial] [introductory series] [III] build tensorflow environment
- 数据库系统原理与应用教程(001)—— MySQL 安装与配置:MySQL 软件的安装(windows 环境)
- Principle of motion capture system
- Idea start command line is too long problem handling
猜你喜欢

Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?

IM即时通讯开发万人群聊消息投递方案

In the past six months, it has been invested by five "giants", and this intelligent driving "dark horse" is sought after by capital

全面看待企业数字化转型的价值

Activity的生命周期和启动模式详解

How to restore the system of Sony laptop

Principle of motion capture system

What is the digital transformation of manufacturing industry

Submission lottery - light application server essay solicitation activity (may) award announcement

Tutorial on the principle and application of database system (002) -- MySQL installation and configuration: MySQL software uninstallation (Windows Environment)
随机推荐
Germany if was crowned with many awards. How strong is this pair of headphones? In depth evaluation of yinpo GTW 270 hybrid
Principle of motion capture system
Learn selenium to simulate mouse operation, and you can be lazy a little bit
How to use F1 to F12 correctly on laptop keyboard
Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)
【SQL语句】请问这边为什么select出了两个上海,查询出了不同的count我想让他变成一个上海,count只显示一个总和
【Hot100】17. 电话号码的字母组合
Go 语言怎么使用对称加密?
Authentication processing in interface testing framework
Basic use of MySQL
How to use phpipam to manage IP addresses and subnets
Go language source level debugger delve
【直播预约】数据库OBCP认证全面升级公开课
模板引擎Velocity 基礎
Go 语言错误处理为什么更推荐使用 pkg/errors 三方库?
数据库系统原理与应用教程(006)—— 编译安装 MySQL5.7(Linux 环境)
Rhcsa Road
Why is the pkg/errors tripartite library more recommended for go language error handling?
Défaillance lors du démarrage de la machine virtuelle VMware: le poste de travail VMware n'est pas compatible avec hyper - V...
How to repair the laptop that cannot connect to the wireless network