当前位置:网站首页>kotlin 匿名函数 与 Lambda
kotlin 匿名函数 与 Lambda
2022-06-24 12:50:00 【华为云】
@[TOC](匿名函数 与 Lambda)
前言
匿名函数,顾名思义,就是没有名的函数
1、匿名函数
匿名函数
val len = "tiger".count(); println(len); val len2 = "tiger".count {// it 等价于 t i g e r 的字符 char it == 'g' } println(len2);2、函数类型与隐式返回
函数类型的隐式返回
// 第一步:函数输入输出的声明 val methodAction: () -> String// 第二步:对上面函数的实现 methodAction = { val inputValue = 666// 匿名函数,不要写return, 最后一行就是返回值 "$inputValue tiger" }// 第三步:调用函数 println(methodAction());3、函数参数
// 可以直接将上面的 第一步:函数输入输出的声明 和 第二步:对上面函数的实现 合并 val methodAction: (Int, Int, Int) -> String = { number1, number2, number3 -> val inputValue = 666 "$inputValue tiger 参数一:$number1 参数二:$number2 参数三:$number3" }// 第三步:调用函数 println(methodAction(1, 2, 3))4、it 关键字特点
// 在kotlin中 如果传入的参数只有一个,kotlin 都会自动生成一个it 隐式参数 val methodAction: (String) -> String = { "$it tiger" } println(methodAction("666")) val methodAction2: (Double) -> String = { "$it tiger" } println(methodAction2(666.0)) val methodAction3: (Int) -> String = { "$it tiger" } println(methodAction3(666))5、匿名函数的类型推断
// 匿名函数,类型推断为String (返回类型,根据返回参数而定,可返回任意类型的参数)// 方法名 : 必须指定 参数类型 和 返回类型// 方法名 = 类型推断返回类型 val methodValue = { num1: Double, num2: Float, num3: Int -> "num1: $num1, num2: $num2: num3: $num3" } println(methodValue(32.2, 33.4f, 44))6、Lambda
匿名函数 属于Lambda
// 匿名函数 == Lambda 表达式 val addResultMethod = {number1: Int, number2: Int -> "两个求和 ${number1 + number2}" } println(addResultMethod(3, 6)) // 匿名函数 入参 Int 返回Any 类型 (Any 类型于Java 中的 Object )// Lambda 表达式的参数 Int, Lambda 表达式的结果Any 类型 val weakResultMethod = {number: Int -> when(number){ 1 -> "周一" 2 -> "周二" 3 -> "周三" 4 -> "周四" 5 -> "周五" else -> -1 } } // weakResultMethod 函数 (Int) -> Any println(weakResultMethod(3))7、函数中定义参数 是函数的函数
// 调用函数 loginAPI("tiger", "123456"){ msg: String, code: Int -> println("最终的登录情况是:msg: $msg code: $code") }// 模拟服务器的数据const val USER_NAME_SAVE_DB = "tiger"const val USER_PASS_SAVE_DB = "123456"// 模仿前端登录fun loginAPI(userName: String, passWord: String, responseResult: (String, Int) -> Unit) { if (userName == null || passWord == null){ // 出现问题,终止程序 抛出异常 Nothing(是一个编译期的抽象概念,只有需要将一个函数显示的标记为无法完成时,才有用到Nothing类型的必要) TODO("用户名或密码错误") } if (userName.length > 3 && passWord.length > 3){ if (wbeServerLoginApi(name = userName, pwd = passWord)){ responseResult("login success", 200) }else{ responseResult("login error", 500) } }else{ TODO("用户名或密码错误") }}// 模拟登录操作private fun wbeServerLoginApi(name: String, pwd: String): Boolean { return name == USER_NAME_SAVE_DB && pwd == USER_PASS_SAVE_DB}8、函数内联
如果函数参数有Lambda ,尽量使用 inline 关键字,这样内部会做优化,减少函数开辟,对象开辟,的性能损耗
使用内联,相当于C++ #define 宏定义,宏替换,会把代码替换到调用处,没有任何函数的开辟, 对象的开辟,造成性能损耗
如果不使用内联,在调用端,会生成多个对象来完成Lambda 的调用(造成性能损耗)
// 模仿前端登录 inline 内联关键字inline fun loginAPI(userName: String, passWord: String, responseResult: (String, Int) -> Unit) { if (userName == null || passWord == null){ // 出现问题,终止程序 抛出异常 Nothing(是一个编译期的抽象概念,只有需要将一个函数显示的标记为无法完成时,才有用到Nothing类型的必要) TODO("用户名或密码错误") } if (userName.length > 3 && passWord.length > 3){ if (wbeServerLoginApi(name = userName, pwd = passWord)){ responseResult("login success", 200) }else{ responseResult("login error", 500) } }else{ TODO("用户名或密码错误") }}9、函数引用
// Lambda 属于函数类型对象,需要把methodResponseResult 普通函数 通过 :: 转变成 函数类型的对象(函数引用) loginAPI("tiger", "123456", ::methodResponseResult)//定义一个函数fun methodResponseResult(msg: String, code: Int){ println("最终的登录情况是:msg: $msg code: $code")}// 模拟服务器的数据const val USER_NAME_SAVE_DB = "tiger"const val USER_PASS_SAVE_DB = "123456"// 模仿前端登录inline fun loginAPI(userName: String, passWord: String, responseResult: (String, Int) -> Unit) { if (userName == null || passWord == null){ // 出现问题,终止程序 抛出异常 Nothing(是一个编译期的抽象概念,只有需要将一个函数显示的标记为无法完成时,才有用到Nothing类型的必要) TODO("用户名或密码错误") } if (userName.length > 3 && passWord.length > 3){ if (wbeServerLoginApi(name = userName, pwd = passWord)){ responseResult("login success", 200) }else{ responseResult("login error", 500) } }else{ TODO("用户名或密码错误") }}// 模拟登录操作fun wbeServerLoginApi(name: String, pwd: String): Boolean { return name == USER_NAME_SAVE_DB && pwd == USER_PASS_SAVE_DB}10、函数类型作为返回类型
val showMethod = show("tiger")// showMethod 是 show 函数的返回值,只不过这个返回值,是一个函数// show == 匿名函数 println(showMethod("王漂亮", 18))fun show(info: String) :(String, Int) -> String { println("我是show 函数 info: $info") return {name: String, age: Int -> "里面的 name: $name, age: $age" }}11、匿名函数和具名函数
// 匿名函数 showPersonInfo("tiger", 18, '男', "学习kotlin"){ println("显示结果: $it") }// 具名函数 show showPersonInfo("tiger", 18, '男', "学习kotlin", ::showResultImpl)fun showResultImpl(result: String){ println("具名函数的显示结果: $result")}inline fun showPersonInfo(name: String, age: Int, sex: Char, study: String, showResult: (String) -> Unit){ val str = "name: $name, age: $age, sex: $sex, study: $study" showResult(str)}总结
🤩
️
边栏推荐
- LVGL库入门教程 - 颜色和图像
- #云原生征文#Ingress案例实战
- 初中级开发如何有效减少自身的工作量?
- What should I do if I fail to apply for the mime database? The experience from failure to success is shared with you ~
- Implement Domain Driven Design - use ABP framework - create entities
- CPU status information us, sy and other meanings
- How does webrtc obtain video stream data on the C ++ side?
- 1、贪吃蛇游戏设计
- Configure Yum proxy
- CPU process priority
猜你喜欢

Several common DoS attacks

一文讲透研发效能!您关心的问题都在

脚本之美│VBS 入门交互实战

AGCO AI frontier promotion (6.24)

3. Caller 服务调用 - dapr

go Cobra命令行工具入门

Developer survey: rust/postgresql is the most popular, and PHP salary is low

Creation and use of unified links in Huawei applinking

青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”

Golden age ticket: Web3.0 Security Manual
随机推荐
如何避免严重网络安全事故的发生?
一文讲透研发效能!您关心的问题都在
LVGL库入门教程 - 颜色和图像
TCP triple handshake
Kubernetes集群部署
Prometheus PushGateway 碎碎念
Evolution of the message module of the play live series (3)
Why is open source technology so popular in the development of audio and video streaming media platform?
3. caller service call - dapr
"Interesting" is the competitiveness of the new era
谁是鱼谁是饵?红队视角下蜜罐识别方式汇总
Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer
Developer survey: rust/postgresql is the most popular, and PHP salary is low
The difference between apt and apt get
不用Home Assistant,智汀也开源接入HomeKit、绿米设备?
Integrate the authorization interface code of intra city distribution account of multiple express companies nationwide - Express 100
Megacli online management raid installation and use steps
I have fundamentally solved the problem of wechat occupying mobile memory
CPU status information us, sy and other meanings
华为AppLinking中统一链接的创建和使用