当前位置:网站首页>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
🤩
️
边栏推荐
- The second phase of freshman engineering education seminar is to enroll in the China 100 school peer program
- How to efficiently analyze online log
- 美国会参议院推进两党枪支安全法案
- Internet of things? Come and see Arduino on the cloud
- AGCO AI frontier promotion (6.24)
- Cmput 379 explanation
- 手机开户后多久才能通过?在线开户安全么?
- Getting started with the go Cobra command line tool
- [data mining] final review (sample questions + a few knowledge points)
- Implement Domain Driven Design - use ABP framework - create entities
猜你喜欢

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

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

Main steps of system test

Detailed explanation of abstractqueuedsynchronizer, the cornerstone of thread synchronization

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

Teach you how to use airtestide to connect your mobile phone wirelessly!

Use terminal to activate CONDA service in pypharm (the ultimate method is definitely OK)

nifi从入门到实战(保姆级教程)——环境篇

Golden age ticket: Web3.0 Security Manual

Use abp Zero builds a third-party login module (I): Principles
随机推荐
黄金年代入场券之《Web3.0安全手册》
CVPR 2022 - Interpretation of selected papers of meituan technical team
服务可见可观测性
[log service CLS] Tencent cloud log service CLS accesses CDN
LVGL库入门教程 - 颜色和图像
SYSTEMd common component description
Introduction to reptile to give up 01: Hello, reptile!
The agile way? Is agile development really out of date?
About the hacked database
kotlin 接口 泛型 协变 逆变
Implement Domain Driven Design - use ABP framework - update operational entities
爱可可AI前沿推介(6.24)
Nifi from introduction to practice (nanny level tutorial) - environment
How stupid of me to hire a bunch of programmers who can only "Google"!
金鱼哥RHCA回忆录:DO447管理清单和凭据--为访问清单主机创建机器凭据
使用 Abp.Zero 搭建第三方登录模块(一):原理篇
C语言中常量的定义和使用
Cohere、OpenAI、AI21联合发布部署模型的最佳实践准则
Implement Domain Driven Design - use ABP framework - create entities
Manuel d'entrevue du gestionnaire de l'analyse des sources