当前位置:网站首页>Kotlin anonymous function and lambda
Kotlin anonymous function and lambda
2022-06-24 13:35:00 【Hua Weiyun】
@[TOC]( Anonymous functions And Lambda)
Preface
Anonymous functions , seeing the name of a thing one thinks of its function , Is a function without a name
1、 Anonymous functions
Anonymous functions
val len = "tiger".count(); println(len); val len2 = "tiger".count {// it Equivalent to t i g e r The characters of char it == 'g' } println(len2);2、 Function type and implicit return
Implicit return of function type
// First step : Declaration of function input and output val methodAction: () -> String// The second step : The implementation of the above functions methodAction = { val inputValue = 666// Anonymous functions , Do not write return, The last line is the return value "$inputValue tiger" }// The third step : Call function println(methodAction());3、 Function parameter
// You can directly put the above First step : Declaration of function input and output and The second step : The implementation of the above functions Merge val methodAction: (Int, Int, Int) -> String = { number1, number2, number3 -> val inputValue = 666 "$inputValue tiger Parameter one :$number1 Parameter two :$number2 Parameter 3 :$number3" }// The third step : Call function println(methodAction(1, 2, 3))4、it Keyword features
// stay kotlin in If there is only one parameter passed in ,kotlin Will automatically generate a it Implicit parameter 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、 Type inference of anonymous functions
// Anonymous functions , The type is inferred as String ( Return type , Depending on the return parameters , Any type of parameter can be returned )// Method name : Must specify Parameter type and Return type // Method name = Type inference return type val methodValue = { num1: Double, num2: Float, num3: Int -> "num1: $num1, num2: $num2: num3: $num3" } println(methodValue(32.2, 33.4f, 44))6、Lambda
Anonymous functions Belong to Lambda
// Anonymous functions == Lambda expression val addResultMethod = {number1: Int, number2: Int -> " Two sums ${number1 + number2}" } println(addResultMethod(3, 6)) // Anonymous functions Enter the reference Int return Any type (Any Type on Java Medium Object )// Lambda The argument to the expression Int, Lambda Result of expression Any type val weakResultMethod = {number: Int -> when(number){ 1 -> " Monday " 2 -> " Tuesday " 3 -> " Wednesday " 4 -> " Thursday " 5 -> " Friday " else -> -1 } } // weakResultMethod function (Int) -> Any println(weakResultMethod(3))7、 Function to define parameters Is a function of a function
// Call function loginAPI("tiger", "123456"){ msg: String, code: Int -> println(" The final login is :msg: $msg code: $code") }// Simulate the data of the server const val USER_NAME_SAVE_DB = "tiger"const val USER_PASS_SAVE_DB = "123456"// Imitate front-end login fun loginAPI(userName: String, passWord: String, responseResult: (String, Int) -> Unit) { if (userName == null || passWord == null){ // Problems arise , To terminate the program Throw an exception Nothing( Is an abstract concept at compile time , Only when you need to mark a function as incomplete , To be useful to Nothing Necessity of type ) TODO(" Wrong user name or password ") } if (userName.length > 3 && passWord.length > 3){ if (wbeServerLoginApi(name = userName, pwd = passWord)){ responseResult("login success", 200) }else{ responseResult("login error", 500) } }else{ TODO(" Wrong user name or password ") }}// Simulate login operation private fun wbeServerLoginApi(name: String, pwd: String): Boolean { return name == USER_NAME_SAVE_DB && pwd == USER_PASS_SAVE_DB}8、 Function inlining
If the function argument has Lambda , Use as much as possible inline keyword , In this way, internal optimization will be done , Reduce the number of functions , Object development , Loss of performance
Use inline , amount to C++ #define Macro definition , Macro replace , Will replace the code with the calling code , There is no development of any function , Object development , Cause loss of performance
If inline is not used , On the calling side , Multiple objects will be generated to complete Lambda Call to ( Cause loss of performance )
// Imitate front-end login inline Inline keyword inline fun loginAPI(userName: String, passWord: String, responseResult: (String, Int) -> Unit) { if (userName == null || passWord == null){ // Problems arise , To terminate the program Throw an exception Nothing( Is an abstract concept at compile time , Only when you need to mark a function as incomplete , To be useful to Nothing Necessity of type ) TODO(" Wrong user name or password ") } if (userName.length > 3 && passWord.length > 3){ if (wbeServerLoginApi(name = userName, pwd = passWord)){ responseResult("login success", 200) }else{ responseResult("login error", 500) } }else{ TODO(" Wrong user name or password ") }}9、 Function reference
// Lambda Objects of function type , Need to put methodResponseResult Ordinary function adopt :: Into a Object of function type ( Function reference ) loginAPI("tiger", "123456", ::methodResponseResult)// Define a function fun methodResponseResult(msg: String, code: Int){ println(" The final login is :msg: $msg code: $code")}// Simulate the data of the server const val USER_NAME_SAVE_DB = "tiger"const val USER_PASS_SAVE_DB = "123456"// Imitate front-end login inline fun loginAPI(userName: String, passWord: String, responseResult: (String, Int) -> Unit) { if (userName == null || passWord == null){ // Problems arise , To terminate the program Throw an exception Nothing( Is an abstract concept at compile time , Only when you need to mark a function as incomplete , To be useful to Nothing Necessity of type ) TODO(" Wrong user name or password ") } if (userName.length > 3 && passWord.length > 3){ if (wbeServerLoginApi(name = userName, pwd = passWord)){ responseResult("login success", 200) }else{ responseResult("login error", 500) } }else{ TODO(" Wrong user name or password ") }}// Simulate login operation fun wbeServerLoginApi(name: String, pwd: String): Boolean { return name == USER_NAME_SAVE_DB && pwd == USER_PASS_SAVE_DB}10、 Function type as return type
val showMethod = show("tiger")// showMethod yes show The return value of the function , Just this return value , It's a function // show == Anonymous functions println(showMethod(" Wang Meili ", 18))fun show(info: String) :(String, Int) -> String { println(" I am a show function info: $info") return {name: String, age: Int -> " Inside name: $name, age: $age" }}11、 Anonymous and named functions
// Anonymous functions showPersonInfo("tiger", 18, ' male ', " Study kotlin"){ println(" Show results : $it") }// Named functions show showPersonInfo("tiger", 18, ' male ', " Study kotlin", ::showResultImpl)fun showResultImpl(result: String){ println(" Display results of named functions : $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)}summary
🤩
️
边栏推荐
- 发扬连续作战优良作风 全力以赴确保北江大堤安全
- kotlin 关键字 扩展函数
- 源码解析 Handler 面试宝典
- Integrated API interface code of domestic express companies for intra city distribution and ordering - Express 100
- [one picture series] one picture to understand Tencent Qianfan apaas
- 强化学习之父Richard Sutton论文:追寻智能决策者的通用模型
- 华为AppLinking中统一链接的创建和使用
- LVGL库入门教程 - 颜色和图像
- Use abp Zero builds a third-party login module (I): Principles
- kotlin 初始化块
猜你喜欢

首席信息安全官仍然会犯的漏洞管理错误

Understanding openstack network

Brief introduction to cluster analysis

DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中

Comparator 排序函数式接口

Getting started with the go Cobra command line tool

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

3. Caller 服务调用 - dapr

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

Getting started with the lvgl Library - colors and images
随机推荐
Resolve symbol conflicts for dynamic libraries
8 lines of code to teach you how to build an intelligent robot platform
kotlin 初始化块
CVPR 2022 | 美團技術團隊精選論文解讀
黄金年代入场券之《Web3.0安全手册》
"I, an idiot, have recruited a bunch of programmers who can only" Google "
The second phase of freshman engineering education seminar is to enroll in the China 100 school peer program
kotlin 语言特性
Getting started with the go Cobra command line tool
Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer
Beauty of script │ VBS introduction interactive practice
Getting started with the lvgl Library - colors and images
强化学习之父Richard Sutton论文:追寻智能决策者的通用模型
The 35 "top 100 counties" of tmall 618 agricultural products come from the central and western regions and Northeast China
Summary of the process of restoring damaged data in MySQL database
Nifi from introduction to practice (nanny level tutorial) - environment
LVGL库入门教程 - 颜色和图像
这几个默认路由、静态路由的配置部署都不会,还算什么网工!
Gateway processing flow of zuul source code analysis
CPU process priority