当前位置:网站首页>【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函数;
以上分析有不对的地方,请指出,互相学习,谢谢哦!
边栏推荐
- Submission lottery - light application server essay solicitation activity (may) award announcement
- Go 语言错误处理为什么更推荐使用 pkg/errors 三方库?
- UML tourism management system "suggestions collection"
- 博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”
- 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
- 毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
- SQLServer查询: a.id与b.id相同时,a.id对应的a.p在b.id对应的b.p里找不到的话,就显示出这个a.id和a.p
- Origin2018 installation and use (sorting)
- 【观察】数字化时代的咨询往何处走?软通咨询的思与行
- There will be a gap bug when the search box and button are zoomed
猜你喜欢
【Hot100】20. 有效的括号
Zhou Shaojian, rare
Malaysia's Star: Sun Yuchen is still adhering to the dream of digital economy in WTO MC12
How to maintain the laptop battery
Rhcsa Road
She is the "HR of others" | ones character
数据库系统原理与应用教程(001)—— MySQL 安装与配置:MySQL 软件的安装(windows 环境)
Stegano in the world of attack and defense
复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents
随机推荐
数据库系统原理与应用教程(005)—— yum 离线安装 MySQL5.7(Linux 环境)
IM即時通訊開發實現心跳保活遇到的問題
Buuctf gold III
Guide for high-end programmers to fish at work
程序员职业生涯真的很短吗?
Five years after graduation, I became a test development engineer with an annual salary of 30w+
Rhcsa Road
Idea start command line is too long problem handling
投稿开奖丨轻量应用服务器征文活动(5月)奖励公布
接口测试框架中的鉴权处理
The picgo shortcut is amazing. This person thinks exactly the same as me
[daily question] 1175 Prime permutation
Go language source level debugger delve
ABAP call restful API
China's intelligent transportation construction from the perspective of "one hour life circle" in Dawan District
How long will it take to achieve digital immortality? Metacosmic holographic human avatar 8i
Solution to the problem that the keypad light does not light up when starting up
实现数字永生还有多久?元宇宙全息真人分身#8i
How to solve the problem that the battery icon of notebook computer does not display
Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents