当前位置:网站首页>Kotlin -- function
Kotlin -- function
2022-07-28 04:07:00 【Violet and begonia】
One 、 Function header

- Used fun Keyword to define the function ;
- The name of the function , The hump nomenclature is used ( In most cases );
- Function parameter , In order to (name: String) In this form , This means that the parameter type is String type ;
- return type , Immediately after the parameter ;
- Finally, the function body in curly braces , It represents the logic of the whole function .
Two 、 Function parameter
Default value parameter
If you do not intend to pass in parameters , You can set default values for parameters in advancefun doSomething(a: Int=1) { }Named value parameter
fun doSomething(a: Int=1) { } doSomething(a = 2)
3、 ... and 、Unit Function of
If a function does not return any useful values , Its return type is Unit.Unit It's a type that has only one value ——Unit The type of . This value does not need to be explicitly returned . Be similar to void, however Unit Function solves the application in generics .
fun printHello(name: String?): Unit {
if (name != null)
println("Hello $name")
else
println("Hi there!")
// `return Unit` perhaps `return` It's optional
}
Four 、TODO function
TODO The function throws an exception , The return value is Nothing type
public inline fun TODO(reason: String): Nothing = throw NotImplementedError("An operation is not implemented: $reason")
for example
fun sum(a: Int, b: Int):Int {
if (a == null || b == null) {
TODO(" abnormal ")
}
return a + b
}
5、 ... and 、 Anonymous functions
Functions that are defined without names are called anonymous functions
Anonymous functions are usually passed to or returned from other functions as a whole , Specify special rules
val s = "abscsabsa" val count = s.count({ letter -> letter == 'a' })
Anonymous function types and implicit returns

- () -> return type
- Unlike named functions , With a few exceptions , Anonymous functions don't need return Keyword returns data , Anonymous functions implicitly or automatically return the result of the last line of the function body
Anonymous function parameters
Like named functions , Anonymous functions can take no arguments , You can also take one or more parameters of any type
The type of the parameter is defined in the type of the anonymous function
The parameter name is placed in the function definition
val blessingFunction: (String,Int) -> String = { name,age -> }it keyword : When defining an anonymous function with only one parameter , have access to it Keyword indicates parameter name
val blessingFunction: (String) -> String = { "hello $it" }
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

- Type inference also supports anonymous functions with parameters , But anonymous functions Parameter name and parameter type There has to be

When defining parameters, the function of the function
fun showOnBoard(goodsName: String, showDiscount: (String,Int) -> String) {
}
In a nutshell : If a function lambda Parameters last ,, Or the only parameter , Then cover it lambda A pair of parentheses for parameters can be omitted
val blessingFunction = {
"hello"
}
6、 ... and 、 Function inlining
When inlining Kotlin It's an optimization mechanism , With inlining ,JVM No need to use lambda Object instance , Thus, variable memory allocation is avoided . Where need to be lambda, The compiler will copy and paste the function body to where . Otherwise ,JVM Will be the same for all lambda Allocate memory for the variables you deal with , This creates memory overhead , Performance issues .
7、 ... and 、 Function reference
Function references can convert a named function into a value parameter , Use lambda Where the expression is , You can use function references 
8、 ... and 、 Function type as return type

Nine 、 Closure
- stay Kotlin in , Anonymous functions can modify and reference variables defined outside their scope , And one function references the variables of another function ,Kotlin Medium lambda It's a closure

边栏推荐
- @Requiredargsconstructor annotation
- Domestic high hidden free agent crawler code
- Kingbasees Security Guide for Jincang database -- 5.1. database transmission security
- A 404 page source code imitating win10 blue screen
- Dynamic planning - 62. Different paths
- H265/hevc noun explanation -- CTU, CTB, Cu, CB, Tu, PU, TB, Pb, LCU, slice, tile, chroma, luma, I frame, B frame, P frame
- LeetCode 0140. 单词拆分 II
- 金仓数据库KingbaseES安全指南--6.2. 身份验证相关的配置文件
- Iterator function operation of iterator learning
- RT-Thread改变打印串口(在BSP的基础上添加其他功能)
猜你喜欢
![Error no matching function for call to 'std:: exception:: exception (const char [15])' problem solving](/img/d1/2fbdf42cf60b5382b5a35c64b172b9.png)
Error no matching function for call to 'std:: exception:: exception (const char [15])' problem solving

H265/hevc noun explanation -- CTU, CTB, Cu, CB, Tu, PU, TB, Pb, LCU, slice, tile, chroma, luma, I frame, B frame, P frame

servlet使用

Classification cluster analysis

R notes mice

【无标题】

Monotonous stack -- 42. Receiving rain -- a difficult problem that big factories must know

Un7.27: how to successfully build a ruoyi framework project in idea?

Developing rc522 module based on c8t6 chip to realize breathing lamp

Ch340 RTS DTR pin programming drives OLED
随机推荐
Common weak network testing tools
Super easy to use PC end long screenshot tool
Build an "industrial brain" and improve the park's operation, management and service capabilities with "digitalization"!
Detailed explanation of pointer written test questions (C language)
[reach out to Party welfare] the easiest way to scan the H5 page in wechat
conda虚拟环境总结与解读
Leetcode58. Length of the last word
离职前一定要做好这7件事情,少一件都很麻烦。
Basic knowledge of day08 redis
Notes on writing questions in sword finger offer
STC timer is abnormal (how to modify the initial value, the timing time is 100ms)
Cyber Nuwa, how to make digital people?
Leetcode 0140. word splitting II
Program life | test engineers only know a little? Seven shortcuts teach you to learn new technology quickly
Advanced Mathematics (Seventh Edition) Tongji University exercises 3-5 personal solutions
Simple and easy-to-use performance testing tools recommended
金仓数据库KingbaseES安全指南--4 数据访问保护
servlet使用
un7.27:如何在idea中成功搭建若依框架项目?
Dynamic planning - 63. Different paths II