Kotlin函数

简介: Kotlin函数

一、函数定义

 
/*
关键字    函数名          参数类型   返回值类型
 ↓        ↓                ↓       ↓      */
fun helloFunction(name: String): String {
    return "Hello $name !"
}/*   ↑
   花括号内为:函数体
*/

简写

fun helloFunction(name: String): String = "Hello $name !"
fun helloFunction(name: String) = "Hello $name !"

二、函数调用

helloFunction("Kotlin")
helloFunction(name = "Kotlin")

三、函数默认参数

 
fun createUser(
    name: String,
    age: Int,
    gender: Int = 1,
    friendCount: Int = 0,
    feedCount: Int = 0,
    likeCount: Long = 0L,
    commentCount: Int = 0
) {
    //..
}
 
fun createUser(
    name: String,
    age: Int,
    gender: Int = 1,
    friendCount: Int = 0,
    feedCount: Int = 0,
    likeCount: Long = 0L,
    commentCount: Int = 0
) {
    //..
}

有默认值得参数可以不传

 
createUser(
    name = "Tom",
    age = 30,
    commentCount = 3285
)
目录
相关文章
|
3天前
|
Kotlin
Kotlin中的函数分类(顶层、成员、局部、递归等)
Kotlin中的函数分类(顶层、成员、局部、递归等)
7 1
|
3天前
|
Kotlin
Kotlin中的函数定义
Kotlin中的函数定义
10 4
|
2天前
|
Java Kotlin
Kotlin 中的 apply 函数详解
Kotlin 中的 apply 函数详解
4 0
|
2天前
|
设计模式 Java Kotlin
Kotlin 中的 run 函数详解
Kotlin 中的 run 函数详解
5 0
|
2天前
|
Java Kotlin
Kotlin 中的 with 函数简介
Kotlin 中的 with 函数简介
3 0
|
2天前
|
安全 Kotlin
Kotlin中的安全导航操作符?.、空合并运算符?:以及let函数的实践与理解
Kotlin中的安全导航操作符?.、空合并运算符?:以及let函数的实践与理解
3 0
|
2月前
|
Kotlin
Kotlin - 标准函数(with、run和apply)
Kotlin - 标准函数(with、run和apply)
11 1
|
11月前
|
API Kotlin
Kotlin中扩展函数、infix关键字、apply函数和DSL的详解
Kotlin中扩展函数、infix关键字、apply函数和DSL的详解
89 0
|
11月前
|
安全 Java Kotlin
Kotlin中空安全操作符,异常处理和自定义异常,以及先决条件函数详解
Kotlin中空安全操作符,异常处理和自定义异常,以及先决条件函数详解
97 0
|
11月前
|
Java 编译器 Kotlin
Kotlin 中变量,类型,表达式,函数详解
Kotlin 中变量,类型,表达式,函数详解
73 0