当前位置:网站首页>【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函数;
以上分析有不对的地方,请指出,互相学习,谢谢哦!
边栏推荐
- 【Hot100】17. Letter combination of telephone number
- [nodemon] app crashed - waiting for file changes before starting... resolvent
- Im instant messaging develops a message delivery scheme for 10000 people
- 毕业后5年,我成为了年薪30w+的测试开发工程师
- Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
- Analysis of PostgreSQL storage structure
- OJ questions related to complexity (leetcode, C language, complexity, vanishing numbers, rotating array)
- 【直播预约】数据库OBCP认证全面升级公开课
- How to solve the problem that the battery icon of notebook computer does not display
- 瑞典公布决定排除华为5G设备,但是华为已成功找到新出路
猜你喜欢

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

Sweden announced its decision to exclude Huawei 5g equipment, but Huawei has successfully found a new way out

How to solve the keyboard key failure of notebook computer

学会了selenium 模拟鼠标操作,你就可以偷懒点点点了

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

芯片供应转向过剩,中国芯片日产增加至10亿,国外芯片将更难受
![[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting](/img/82/3bb382893682a30e8af130365ec4ef.jpg)
[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting

Problèmes rencontrés dans le développement de la GI pour maintenir le rythme cardiaque en vie

How to use MySQL language for row and column devices?

独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作
随机推荐
Stonedb is building blocks for domestic databases, and the integrated real-time HTAP database based on MySQL is officially open source!
How to optimize repeated if err in go language= Nil template code?
Problems encountered in IM instant messaging development to maintain heartbeat
Tutorial on the principle and application of database system (005) -- Yum offline installation of MySQL 5.7 (Linux Environment)
Telecommuting experience? Let's introduce ourselves ~ | community essay solicitation
Where should older test / development programmers go? Will it be abandoned by the times?
Buuctf gold III
Origin2018 installation and use (sorting)
Idea start command line is too long problem handling
全面看待企业数字化转型的价值
How to solve the problem that the battery icon of notebook computer does not display
苹果自研基带芯片再次失败,说明了华为海思的技术领先性
实现数字永生还有多久?元宇宙全息真人分身#8i
游戏行业安全选择游戏盾,效果怎么样?
數據庫系統原理與應用教程(006)—— 編譯安裝 MySQL5.7(Linux 環境)
Stegano in the world of attack and defense
【Hot100】17. 电话号码的字母组合
博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”
Tutorial on the principle and application of database system (001) -- MySQL installation and configuration: installation of MySQL software (Windows Environment)
Go language source level debugger delve