当前位置:网站首页>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)}总结
🤩
️
边栏推荐
- Preparation and operation & Maintenance Guide for 'high concurrency & high performance & high availability service program'
- 手机开户后多久才能通过?在线开户安全么?
- YOLOv6:又快又准的目标检测框架开源啦
- 我从根上解决了微信占用手机内存问题
- 3. Caller 服务调用 - dapr
- 一文讲透研发效能!您关心的问题都在
- Talk about GC of JVM
- 敏捷之道 | 敏捷开发真的过时了么?
- Why is open source technology so popular in the development of audio and video streaming media platform?
- CVPR 2022 | 美团技术团队精选论文解读
猜你喜欢

Kubernetes集群部署

使用 Abp.Zero 搭建第三方登录模块(一):原理篇

Understanding openstack network

I have fundamentally solved the problem of wechat occupying mobile memory

Definition and use of constants in C language

3. caller service call - dapr

使用 Abp.Zero 搭建第三方登录模块(一):原理篇

CVPR 2022 | 美团技术团队精选论文解读

go Cobra命令行工具入门

CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan
随机推荐
CVPR 2022 | 美团技术团队精选论文解读
快速了解常用的消息摘要算法,再也不用担心面试官的刨根问底
Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer
Can inspection results be entered after the completion of inspection lot UD with long-term inspection characteristics in SAP QM?
Attack Science: ARP attack
Attack popular science: DDoS
如何避免严重网络安全事故的发生?
Implement Domain Driven Design - use ABP framework - update operational entities
Brief introduction to cluster analysis
go Cobra命令行工具入门
Without home assistant, zhiting can also open source access homekit and green rice devices?
Prometheus PushGateway 碎碎念
8 - Format integers and floating point numbers
About the hacked database
面试官:MySQL 数据库查询慢,除了索引问题还可能是什么原因?
Use abp Zero builds a third-party login module (I): Principles
openGauss内核:简单查询的执行
Baidu simian: talk about persistence mechanism and rdb/aof application scenario analysis!
The difference between apt and apt get
Leetcode 1218. Longest definite difference subsequence