当前位置:网站首页>【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. 电话号码的字母组合
- Use Tencent cloud to build a map bed service
- Stegano in the world of attack and defense
- Origin2018安装与使用(整理中)
- IM即时通讯开发万人群聊消息投递方案
- [daily news]what happened to the corresponding author of latex
- [nodemon] app crashed - waiting for file changes before starting...解决方法
- Tutorial on the principle and application of database system (005) -- Yum offline installation of MySQL 5.7 (Linux Environment)
- 虚拟串口模拟器和串口调试助手使用教程「建议收藏」
- 独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作
猜你喜欢

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

PostgreSQL 存储结构浅析
![[nodemon] app crashed - waiting for file changes before starting... resolvent](/img/ee/9830afd86e092851a2a906cb994949.png)
[nodemon] app crashed - waiting for file changes before starting... resolvent

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

OJ questions related to complexity (leetcode, C language, complexity, vanishing numbers, rotating array)

数据库系统原理与应用教程(003)—— MySQL 安装与配置:手工配置 MySQL(windows 环境)

投稿开奖丨轻量应用服务器征文活动(5月)奖励公布

Is the programmer's career really short?

The sharp drop in electricity consumption in Guangdong shows that the substitution of high-tech industries for high-energy consumption industries has achieved preliminary results

怎么用MySQL语言进行行列装置?
随机推荐
Problems encountered in IM instant messaging development to maintain heartbeat
There is a difference between u-standard contract and currency standard contract. Will u-standard contract explode
In the era of super video, what kind of technology will become the base?
Red team Chapter 10: ColdFusion the difficult process of deserializing WAF to exp to get the target
Rhcsa Road
How long will it take to achieve digital immortality? Metacosmic holographic human avatar 8i
从大湾区“1小时生活圈”看我国智慧交通建设
[jetsonnano] [tutorial] [introductory series] [III] build tensorflow environment
Rhcsa Road
Analysis of PostgreSQL storage structure
数据库系统原理与应用教程(005)—— yum 离线安装 MySQL5.7(Linux 环境)
Virtual serial port simulator and serial port debugging assistant tutorial "suggestions collection"
In the past six months, it has been invested by five "giants", and this intelligent driving "dark horse" is sought after by capital
SQLServer查询: a.id与b.id相同时,a.id对应的a.p在b.id对应的b.p里找不到的话,就显示出这个a.id和a.p
[JetsonNano] [教程] [入门系列] [三] 搭建TensorFlow环境
數據庫系統原理與應用教程(006)—— 編譯安裝 MySQL5.7(Linux 環境)
实现数字永生还有多久?元宇宙全息真人分身#8i
IM即時通訊開發實現心跳保活遇到的問題
Mlperf training v2.0 list released, with the same GPU configuration, the performance of Baidu PaddlePaddle ranks first in the world
嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!