当前位置:网站首页>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)}总结
🤩
️
边栏推荐
- Appium installation
- 快速了解常用的消息摘要算法,再也不用担心面试官的刨根问底
- Prometheus PushGateway 碎碎念
- Yolov6: the fast and accurate target detection framework is open source
- On the difference between process and thread
- CVPR 2022 - Interpretation of selected papers of meituan technical team
- Geological disaster early warning monitoring RTU
- 3. caller service call - dapr
- Ask a question about SQL view
- Why does the kubernetes environment require that bridge NF call iptables be enabled?
猜你喜欢

#云原生征文#Ingress案例实战

谁是鱼谁是饵?红队视角下蜜罐识别方式汇总

我从根上解决了微信占用手机内存问题

Creation and use of unified links in Huawei applinking

Interviewer: the MySQL database is slow to query. What are the possible reasons besides the index problem?

1、贪吃蛇游戏设计

Without home assistant, zhiting can also open source access homekit and green rice devices?

不用Home Assistant,智汀也开源接入HomeKit、绿米设备?

I have fundamentally solved the problem of wechat occupying mobile memory

一文理解OpenStack网络
随机推荐
问个sql view的问题
[day ui] affix component learning
我真傻,招了一堆只会“谷歌”的程序员!
实现领域驱动设计 - 使用ABP框架 - 创建实体
LVGL库入门教程 - 颜色和图像
Attack Science: ARP attack
开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
System status identifier 'hum' for SAP QM inspection lot
1、贪吃蛇游戏设计
Go deep into high-performance JSON parsing libraries in go
The second phase of freshman engineering education seminar is to enroll in the China 100 school peer program
Gateway processing flow of zuul source code analysis
openGauss内核:简单查询的执行
"I, an idiot, have recruited a bunch of programmers who can only" Google "
敏捷之道 | 敏捷开发真的过时了么?
C语言中常量的定义和使用
Integrate API interface parameter Dictionary of accounts of multiple local distribution companies - Express 100
Attack popular science: DDoS
天猫618农产品“百强县” 35个县域来自中西部及东北
How to efficiently analyze online log