当前位置:网站首页>Kotlin anonymous functions and functions
Kotlin anonymous functions and functions
2022-04-22 14:43:00 【liujun3512159】
5.1 Anonymous functions
fun main(args: Array<String>) {
println({
val currentYear = 2022
"Welcome to SimVillage, Mayor! (copyright $currentYear)"
}())
}
To define a function is to put an expression or statement in a pair of curly braces
Followed by a pair of empty parentheses , Means calling an anonymous function
5.1.1 Function type
Anonymous functions also have types , be called Function type (function type)
Anonymous functions can be assigned to function type variables as variables
Assigning anonymous functions to variables :
fun main(args: Array<String>) {
val greetingFunction: () -> String = {
val currentYear = 2022
"Welcome to SimVillage, Mayor! (copyright $currentYear)"
}
println(greetingFunction())
}
: () -> String Indicates that the variable stores a function , This function does not require arguments , And the return value is String
5.1.2 Implicit return
Implicit return : Anonymous function will Implicit Or automatically return the result of the last line of the function body
Unlike named functions , Except in rare cases , Anonymous functions don't need return Keyword to return data
Anonymous functions don't have to return The reason for keywords : The compiler does not know whether the returned data comes from a function that calls an anonymous function , Or the function itself
5.1.3 Function parameter
Anonymous parameters can also take one or more parameters of any type
fun main(args: Array<String>) {
val greetingFunction: (String) -> String = { playerName ->
val currentYear = 2022
"Welcome to SimVillage, $playerName! (copyright $currentYear)"
}
println(greetingFunction("Guyal"))
}
In the body of an anonymous function , After the left curly bracket , write String The parameter name of the type , Followed by an arrow symbol
5.1.4 it keyword
When defining an anonymous function with only one parameter , have access to it Keyword to represent the parameter name
fun main(args: Array<String>) {
val greetingFunction: (String) -> String = {
val currentYear = 2022
"Welcome to SimVillage, $it! (copyright $currentYear)"
}
println(greetingFunction("Guyal"))
}
5.1.5 Multiple parameters
it Keyword is only applicable to the case of one parameter , If you have more than one parameter , You need to use named parameters
fun main(args: Array<String>) {
val greetingFunction: (String, Int) -> String = { playerName, numBuildings ->
val currentYear = 2022
println("Adding $numBuildings houses")
"Welcome to SimVillage, $playerName! (copyright $currentYear)"
}
println(greetingFunction("Guyal", 2))
}
Type inference
When defining a variable , If you have assigned an anonymous function to it as a variable , You don't need to show the specified variable type
val greetingFunction = {
val currentYear = 2022
"Welcome to SimVillage, Mayor! (copyright $currentYear)"
}
Type inference also supports anonymous functions with parameters , But anonymous functions must have parameter names and parameter types
fun main(args: Array<String>) {
val greetingFunction = { playerName: String, numBuildings: Int ->
val currentYear = 2022
println("Adding $numBuildings houses")
"Welcome to SimVillage, $playerName! (copyright $currentYear)"
}
println(greetingFunction("Guyal", 2))
}
5.3 Define a function whose parameters are functions
The term :
- lambda: Anonymous functions
- lambda expression : Definition of anonymous function
- lambda result : Data returned by anonymous letter
Functions can also be used as function parameters
fun main(args: Array<String>) {
val greetingFunction = { playerName: String, numBuildings: Int ->
val currentYear = 2022
println("Adding $numBuildings houses")
"Welcome to SimVillage, $playerName! (copyright $currentYear)"
}
runSimulation("Guyal", greetingFunction)
}
fun runSimulation(playerName: String, greetingFunction: (String, Int) -> String) {
val numBuildings = (1..3).shuffled().last() // Randomly selects 1, 2, or 3
println(greetingFunction(playerName, numBuildings))
}
Brief grammar
If a function lambda Parameters last , Then cover it lambda A bunch of parentheses for the value parameter can be omitted
"Mississippi".count({ it == 's' })
It can be abbreviated as
"Mississippi".count { it == 's' }
Again runSimulation You can also use abbreviated syntax to pass in lambda It's worth it : Put values of non function types in parentheses , Put function values and arguments outside parentheses
fun main(args: Array<String>) {
runSimulation("Guyal") { playerName, numBuildings ->
val currentYear = 2022
println("Adding $numBuildings houses")
"Welcome to SimVillage, $playerName! (copyright $currentYear)"
}
}
fun runSimulation(playerName: String, greetingFunction: (String, Int) -> String) {
val numBuildings = (1..3).shuffled().last() // Randomly selects 1, 2, or 3
println(greetingFunction(playerName, numBuildings))
}
5.4 Function inlining
stay JVM On ,lambda Will exist in the form of object instances .JVM Will be the same for all lambda Allocate memory for the variables you deal with , This creates memory overhead
Kotlin Through inline solve lambda Memory overhead caused by , Avoid variable memory allocation
Use the inline method to optimize lambda: With inline Keyword tags use lambda The function of
inline fun runSimulation(playerName: String, greetingFunction: (String, Int) -> String) {
val numBuildings = (1..3).shuffled().last() // Randomly selects 1, 2, or 3
println(greetingFunction(playerName, numBuildings))
}
With inline The key word , call runSimulation Function will not use lambda Object instance : Where to use lambda, The compiler will copy and paste the function body to where
Use lambda Recursive function of cannot be inlined , Because the inline function will make the behavior of copying and pasting the function body infinite loop
5.5 Function reference
Except for the transmission lambda expression ,Kotlin It also provides “ Pass function reference ” Method, the function is passed as a parameter to other functions for use
Use :: + The function name operator obtains the function reference
5.6 Function type as the return value
Closure : Use Define your own Of variables of external functions function
Kotlin Medium lambda Closure
fun configureGreetingFunction(): (String) -> String {
val structureType = "hospitals"
var numBuildings = 5
return { playerName: String ->
val currentYear = 2022
numBuildings += 1
println("Adding $numBuildings $structureType")
"Welcome to SimVillage, $playerName! (copyright $currentYear)"
}
}
5.7 Learn more :Kotlin Medium lambda It's a closure
stay Kotlin in , Anonymous functions can modify and reference variables defined outside their scope . This shows that , Anonymous functions quote To define the variables in the function itself
stay runSimulation Call in println two
fun runSimulation() {
val greetingFunction = configureGreetingFunction()
println(greetingFunction("Guyal"))
println(greetingFunction("Guyal"))
}
Output is :
Adding 6 hospitals
Welcome to SimVillage, Guyal! (copyright 2022)
Adding 7 hospitals
Welcome to SimVillage, Guyal! (copyright 2022)
numBuildings The value of a variable changes from 6 Increased to 7
5.8 Learn more :lambda And anonymous inner classes
Benefits of using function types : Function types allow developers to write less patterned code , Write more flexible code
Java 8 Support object-oriented programming and lambda expression , However, it is not supported to pass a function as a parameter to another function or variable . however Java The alternative is anonymous inner classes —— Defined in class , An unnamed class used to implement a method
Greeting greeting = (palyerName, numBuildings) -> {
int currentYear = 2022;
System.out.println("Adding " + numBuildings + " houses");
return "Welcom to SimVillage, " + playerName + "! (copyright " + currentYear + ")";
};
public interface Greeting {
String greet(String playerName, int numBuildings);
}
greeting.greet("Guyal", 6);
This method and Kotlin Pass on lambda The expression is similar , however Java You need a named interface or class to represent lambda Defined function
版权声明
本文为[liujun3512159]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221434183881.html
边栏推荐
- Knowledge is power, but more importantly, the ability to use knowledge - wechat code scanning payment on the web - technical design
- ArcEngine cannot find this item in this collection
- 数据库资源负载管理(下篇)
- asp.net framework配置swagger并支持上传文件
- 2020 popular whole network series: This is a very suitable Android advanced - interview key and difficult data notes for collection and collection! Continuously update the high-quality interview links
- 远程服务器上共享文件夹的上传与下载
- MapReduce advanced application - full sorting and secondary sorting
- ArcGIS face gap inspection
- asp. Net framework configures swagger and supports uploading files
- Leetcode (04)
猜你喜欢
随机推荐
php 一维数组去重
Android 9,2022-2022字节跳动Android面试真题解析
When allowCredentials is true, allowedOrigins cannot contain the special value “*“ since that canno
人们总是简单的认为产业互联网是一个比互联网还要广大的平台
企业选择私有化部署的IM即时通讯软件,全力保护信息安全!
LeetCode_ 63 different paths II
【ELT.ZIP】OpenHarmony啃论文俱乐部——轻翻那些永垂不朽的诗篇
Awk command
5 minutes to understand the internal implementation of redis QuickList
ArcEngine symbol correlation
2020 popular whole network series: This is a very suitable Android advanced - interview key and difficult data notes for collection and collection! Continuously update the high-quality interview links
ArcGIS face gap inspection
Series interpretation of smc-r (II): smc-r communication technology integrating TCP and RDMA
ArcEngine符号相关
gradle 引用平级项目
【ELT.ZIP】OpenHarmony啃论文俱乐部——一文穿透多媒体过往前沿
Ladder race -- l2-004 is this a binary search tree? (25 points) (recursive)
Android 开发艺术探索笔记(23),2022年Android高级面试题总结
@Resource与构造函数踩坑
Deep understanding of read-write lock reentrantreadwritelock and concurrent container copyonwritearraylist







