当前位置:网站首页>【Kotlin】高阶函数介绍
【Kotlin】高阶函数介绍
2022-07-01 16:18:00 【程序员小何SS】
什么是高阶函数
将函数作为参数或者返回值的,称高阶函数。
定义高阶函数
action是一个高阶函数,(Int) -> Int表示是函数的类型,(Int)表示函数入参类型为Int,后面的Int表示函数返回类型。
private fun init() {
val action: ((Int) -> Int) = {//函数进行加100运算
it + 100
}
}
函数作为参数
以下代码,init函数调用doSomething函数,将Int类型 0 以及action函数传入doSomething。doSomething函数先对入参0进行加200运算,然后调用高阶函数action(进行加100运算),最后打印结果actionResult。 是不是有点策略设计模式的味道?是的,完全可以用它来实现策略设计模式。
private fun init() {
val action: ((Int) -> Int) = {//函数进行加100运算
it + 100
}
doSomething(0, action)//将0以及action传给doSomething
}
private fun doSomething(d: Int, action: (Int) -> Int) {
val data = d + 200//先对d进行加200运算
val actionResult = action(data)//将加200后的结果传给action,结果保存在actionResult中
Log.e("test", "actionResult=${actionResult}")//打印结果
}
函数作为返回值
以下代码,根据不同的类型type,返回对应的action,接着对参数0进行运算,最后打印结果。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val action = init("方案1")
//获取到对应的action,传入参数0进行运算
val result = action?.invoke(0)
//打印结果
Log.e("test", "result=${result}")
}
private fun init(type: String): ((Int) -> Int)? {
val action1: ((Int) -> Int) = {//加100运算
it + 100
}
val action2: ((Int) -> Int) = {//加200运算
it + 200
}
//根据类型type,返回对应的action
return when (type) {
"方案1" -> action1
"方案2" -> action2
else -> null
}
}
lamdba表达式
也是高阶函数,只不过函数是匿名的。以下代码功能跟上述一样,只不过用amdba表达式代替了定义action函数。
private fun init() {
doSomething(0) { //将0以及lambda表达式传给doSomething
it + 100//进行加100运算,并返回
}
}
private fun doSomething(d: Int, action: (Int) -> Unit) {
val data = d + 200//先对d进行加200运算
val actionResult = action(data)//将加200后的结果传给action,结果保存在actionResult中
Log.e("test", "actionResult=${actionResult}")//打印结果
}
高阶函数本质是什么呢?
将第一个例子反编译
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);
}
- 注释1:Kotlin编译器将高阶函数转成Function1;
- 注释2:对应高阶函数的实现;
- 注释3:调用高阶函数,其实就是触发invoke函数;
以上分析有不对的地方,请指出,互相学习,谢谢哦!
边栏推荐
猜你喜欢

Zhou Shaojian, rare

Principle of motion capture system

Germany if was crowned with many awards. How strong is this pair of headphones? In depth evaluation of yinpo GTW 270 hybrid

There will be a gap bug when the search box and button are zoomed

Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)

Tutorial on the principle and application of database system (001) -- MySQL installation and configuration: installation of MySQL software (Windows Environment)

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

数据库系统原理与应用教程(002)—— MySQL 安装与配置:MySQL 软件的卸载(windows 环境)

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

Rhcsa Road
随机推荐
What is the digital transformation of manufacturing industry
如何使用phpIPAM来管理IP地址和子网
程序员职业生涯真的很短吗?
IM即時通訊開發實現心跳保活遇到的問題
怎么用MySQL语言进行行列装置?
[nodemon] app crashed - waiting for file changes before starting... resolvent
VMware 虚拟机启动时出现故障:VMware Workstation 与 Hyper-v 不兼容...
Go 语言怎么优化重复的 if err != nil 样板代码?
制造业数字化转型究竟是什么
VMware virtual machine failed during startup: VMware Workstation is incompatible with hyper-v
Red team Chapter 8: blind guess the difficult utilization process of the package to upload vulnerabilities
德国iF多项大奖加冕,这副耳机有多强?音珀GTW 270 Hybrid深度评测
Apple's self-developed baseband chip failed again, which shows Huawei Hisilicon's technological leadership
How to restore the system with one click on Lenovo laptop
Preliminary study on golang crawler framework
Basic use of MySQL
Solution to the problem that the keypad light does not light up when starting up
There is a difference between u-standard contract and currency standard contract. Will u-standard contract explode
Problems encountered in IM instant messaging development to maintain heartbeat
博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”