Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Functions

Kotlin Functions

Functions are the basic unit of code organization: they encapsulate a piece of logic under a name so it can be called repeatedly.

Kotlin functions are far more flexible than Java's: default parameter values, named arguments, varargs, local functions, tail recursion, and infix calls, plus expression bodies for shorter syntax.

This page starts with the most basic function definitions and focuses on when the return type can be omitted and when it must be written.


Function definition and return values

Kotlin defines functions with the fun keyword; parameters go in parentheses in the form name: Type.

A function body has two forms: a block body wrapped in curly braces, and an expression body that gives the result directly with an equals sign.

Example

// File path: FunctionBasic.kt

// Block body: has curly braces and return, so the return type must be written explicitly

fun add

(

a

:

Int, b

:

Int

)

:

Int

{

   

return

a

b

}

// Expression body: gives the result directly with =, and the return type can be inferred as Int

fun sub

(

a

:

Int, b

:

Int

)

=

a

b

// Block body with no return value: returns Unit by default, so : Unit can be omitted

fun printSum

(

a

:

Int, b

:

Int

)

{

    println

(

"$a + $b = ${a + b}"

)

}

fun main

(

)

{

    println

(

add

(

1

,

2

)

)

     

// Call the block-body function

    println

(

sub

(

5

,

3

)

)

     

// Call the expression-body function

    printSum

(

2

,

3

)

}

The output is as follows.



3

2

2 + 3 = 5

Regarding return types, a common claim online is that "public functions must declare a return type", which is inaccurate.

The accurate rule is: an expression body's return type can always be inferred regardless of visibility; only a block body whose return type is not Unit requires an explicit declaration.

Syntax Must I declare the return type Description
fun f() = a + b Not required Expression body: public, internal, and private can all be inferred
fun f(): Int { return a + b } Must Block body returning non-Unit: the compiler does not infer across statements
fun f() { println(a) } Not required Block body returning Unit: : Unit can be omitted

Tip:Although an expression body may omit the return type, if the function is a public API of a library, writing the return type explicitly improves readability and prevents accidentally changing the exposed type when the implementation is modified.


Single-expression functions

When a function body has only one expression, you can omit the curly braces and return, writing it as a single-expression function.

This is a very common style in Kotlin and is especially concise when combined with a when expression.

Example

// Write the return type explicitly for better readability

fun

double

(

x

:

Int

)

:

Int

=

x

2

// The return type can also be omitted and inferred as Int by the compiler

fun square

(

x

:

Int

)

=

x

x

// Combined with a when expression, it replaces a long if-else chain

fun describe

(

value

:

Int

)

=

when

{

    value

<

0

->

"Negative"

value

==

0

->

"Zero"

else

->

"Positive number"

}

fun main

(

)

{

    println

(

double

(

4

)

)

    println

(

square

(

4

)

)

    println

(

describe

(

1

)

)

    println

(

describe

(

0

)

)

    println

(

describe

(

7

)

)

}



8

16

负数

零

正数

Single-expression and block-body functions are semantically equivalent; the choice mainly depends on the length of the body: logic longer than one line is usually clearer as a block body.


Parameter default values

Kotlin lets you specify default values for parameters so callers can omit them.

It replaces the role of many overloaded methods in Java, letting one function handle several calling styles.

Example

// Both parameters have default values

fun greet

(

name

:

String

=

"Runoob"

, site

:

String

=

"www.runoob.com"

)

:

String

{

   

return

"Welcome $name to $site"

}

fun main

(

)

{

    println

(

greet

(

)

)

                           

// Use default values for both parameters

    println

(

greet

(

"RUNOOB"

)

)

                   

// Override only the first parameter

    println

(

greet

(

site

=

"kotlin.runoob.com"

)

)

 

// Override only the second parameter, using a named argument

}



欢迎 Runoob 访问 www.runoob.com

欢迎 RUNOOB 访问 www.runoob.com

欢迎 Runoob 访问 kotlin.runoob.com

A parameter with a default value can appear before one without a default, but callers must then use a named argument to skip it.

Example

// value has a default value but is written before unit

fun format

(

value

:

Int

=

0

, unit

:

String

)

:

String

=

"$value$unit"

fun main

(

)

{

   

// You cannot write format("px"), because that would pass the string to value and cause a type mismatch

    println

(

format

(

unit

=

"px"

)

)

    println

(

format

(

12

,

"px"

)

)

}



0px

12px

Note:When overriding a superclass method you cannot specify a default value again; the overridden method always uses the default declared in the superclass. Also, default parameters are invisible to Java callers and require @JvmOverloads to generate overloads; this is covered in the chapter "Kotlin Java interoperability".


named parameters

Passing arguments in the form name = value when calling a function is called a named argument.

Named arguments let you reorder arguments and set only the ones you care about, noticeably improving readability.

Example

fun createSite

(

name

:

String

, url

:

String

, port

:

Int

=

80

)

:

String

{

   

return

"$name -> $url:$port"

}

fun main

(

)

{

   

// Reordering still matches correctly

    println

(

createSite

(

url

=

"www.runoob.com"

, name

=

"Runoob"

)

)

   

// Mixing positional and named arguments: positional arguments must come before named ones

    println

(

createSite

(

"RUNOOB"

, url

=

"www.runoob.com"

, port

=

443

)

)

}



Runoob -> www.runoob.com:80

RUNOOB -> www.runoob.com:443

The greatest value of named arguments is eliminating the "too many parameters to tell which is which" problem, especially for functions with several consecutive parameters of the same type.

Note that Java methods do not retain parameter names after compilation, so named arguments cannot be used when calling Java methods.


Varargs (vararg) and the spread operator

vararg means the parameter can accept any number of values; inside the function it is treated as an array.

A function can have only one vararg parameter, and it is usually the last one.

Example

// vararg numbers is of type IntArray inside the function

fun total

(

vararg numbers

:

Int

)

:

Int

{

    var sum

=

0

   

for

(

number in numbers

)

{

        sum

+=

number

   

}

   

return

sum

}

fun main

(

)

{

    println

(

total

(

1

,

2

,

3

)

)

     

// Pass three values

    println

(

total

(

)

)

             

// Pass none, and the array is empty

    println

(

total

(

10

,

20

,

30

,

40

)

)

   

// When you already have an array, use the spread operator * to split it into separate arguments

    val values

=

intArrayOf

(

100

,

200

)

    println

(

total

(

values

)

)

}



6

0

100

300

The spread operator * works only on arrays (including primitive arrays like IntArray), not directly on a List.

Example

fun total

(

vararg numbers

:

Int

)

:

Int

=

numbers.

sum

(

)

fun main

(

)

{

    val list

=

listOf

(

1

,

2

,

3

)

   

// Wrong form: total(*list) does not compile

   

// The correct approach is to convert to an array first and then spread

    println

(

total

(

list.

toIntArray

(

)

)

)

}



6

If a vararg parameter is not the last one, the parameters after it must be passed as named arguments, otherwise the compiler cannot tell which values belong to the vararg.


The Unit return type

A function with no return value has return type Unit, which can be understood as "a type with only one instance".

In Kotlin, Unit is a real type, not a keyword like Java's void.

Example

// Writing : Unit explicitly is exactly equivalent to omitting it

fun sayHello

(

)

:

Unit

{

    println

(

"Hello, Runoob!"

)

}

// Both of the following functions have return type Unit

fun log1

(

)

{

    println

(

"RUNOOB"

)

}

fun log2

(

)

:

Unit

=

println

(

"RUNOOB"

)

fun main

(

)

{

    sayHello

(

)

    log1

(

)

   

// Unit is a type, so a variable can hold it

    val result

:

Unit

=

log2

(

)

    println

(

result

)

}



Hello, Runoob!

RUNOOB

RUNOOB

kotlin.Unit

Precisely because Unit is a type, a function returning Unit can be passed as a value of type () -> Unit, which is the basis of lambdas and higher-order functions.


Local functions

You can define a function inside another function; such a function is called a local function.

A local function is only visible within the body of the function that defines it, and it can access the outer parameters and local variables.

Example

// Top-level function: written directly in the file

fun factorial

(

n

:

Int

)

:

Long

{

   

// Local function: defined inside factorial and can access the outer n

    fun multiply

(

current

:

Int, acc

:

Long

)

:

Long

{

       

return

if

(

current

==

1

)

acc

else

multiply

(

current

1

, acc

current

)

   

}

   

// A local function can also use an expression body, and its return type can be inferred too

    fun describe

(

)

=

"Computing the factorial of $n"

    println

(

describe

(

)

)

   

return

multiply

(

n, 1L

)

}

fun main

(

)

{

    println

(

factorial

(

5

)

)

}



计算 5 的阶乘

120

Local functions are often used to extract logic needed only within the current function, avoiding pollution of the file-level namespace and making the code structure clearer.


Tail recursion with tailrec

If the last operation of a function is a call to itself, the compiler can replace recursion with a loop, avoiding stack overflow; this is tail-recursion optimization.

Marking a function with tailrec tells the compiler to attempt this optimization.

Example

// The recursive call is the last operation, so it can benefit from tailrec optimization

tailrec fun gcd

(

a

:

Int, b

:

Int

)

:

Int

{

   

return

if

(

b

==

0

)

a

else

gcd

(

b, a

%

b

)

}

// Ordinary recursion: the last step is multiplication rather than a call to itself, so tailrec cannot be used

fun factorial

(

n

:

Int

)

:

Long

{

   

return

if

(

n

<=

1

)

1L

else

n

factorial

(

n

1

)

}

fun main

(

)

{

    println

(

gcd

(

48

,

18

)

)

    println

(

factorial

(

5

)

)

}



6

120

The conditions for tailrec are: the recursive call must be the last operation executed in the function body and must not be wrapped in try/catch/finally.

Note:If you add tailrec but no qualifying tail call is found, the compiler issues a warning that the function did not actually get optimized. In that case, check whether the recursive call is wrapped by other operations.


Top-level functions and member functions

A function written directly in a file is a top-level function; one defined inside a class or object is a member function.

The biggest difference is that a member function must be called through an instance, while a top-level function can be called directly.

Example

// Top-level function: does not belong to any class

fun topLevel

(

)

:

String

=

"I am a top-level function"

class

Site

(

val name

:

String

)

{

   

// Member function: must be accessed through an instance

    fun describe

(

)

:

String

=

"Site: $name"

   

// A member function can call a top-level function directly

    fun info

(

)

=

"${describe()} / ${topLevel()}"

}

fun main

(

)

{

    println

(

topLevel

(

)

)

    val runoob

=

Site

(

"Runoob"

)

    println

(

runoob.

describe

(

)

)

    println

(

runoob.

info

(

)

)

}



我是顶层函数

站点:Runoob

站点:Runoob / 我是顶层函数

On the JVM, top-level functions in the same file are compiled into a class named FileNameKt; for example, top-level functions in FunctionBasic.kt go into FunctionBasicKt.


function overloading

Functions with the same name can coexist as long as their parameter lists differ; this is called function overloading.

The compiler decides which one to call based on the types and number of arguments.

Example

// Different parameter types

fun format

(

value

:

Int

)

=

"Integer: $value"

fun format

(

value

:

Double

)

=

"Decimal: $value"

// Different number of parameters

fun format

(

value

:

String

, upper

:

Boolean

)

=

if

(

upper

)

value.

uppercase

(

)

else

value

fun main

(

)

{

    println

(

format

(

42

)

)

    println

(

format

(

3.14

)

)

    println

(

format

(

"runoob"

,

true

)

)

    println

(

format

(

"runoob"

,

false

)

)

}



整数:42

小数:3.14

RUNOOB

runoob

Overloading considers only the parameter list; the return type is not used for differentiation. The following form is illegal and the compiler reports Conflicting overloads.

Example

// Wrong example: only the return type differs, so it does not compile

// fun value(): Int = 1

// fun value(): String = "1"

Tip:Do not design overloads distinguished only by default parameters, such as show(value: Int) and show(value: Int, prefix: String = ""). Such overloads tend to leave both callers and readers unsure which version is actually called.


Infix functions (infix)

A function marked infix can be called in the form a functionName b, omitting the dot and parentheses.

The standard library's to, and, and shl are all infix functions.

Example

class

Site

(

val name

:

String

)

{

   

// Member infix function: must have exactly one parameter

    infix fun hostedAt

(

domain

:

String

)

:

String

=

"$name is hosted on $domain"

}

// Extension infix function: adds infix call capability to an existing type

infix fun Int.

biggerThan

(

other

:

Int

)

:

Boolean

=

this

other

fun main

(

)

{

    val runoob

=

Site

(

"Runoob"

)

   

// The following two forms are completely equivalent

    println

(

runoob.

hostedAt

(

"www.runoob.com"

)

)

    println

(

runoob hostedAt

"www.runoob.com"

)

   

// Equivalent to 10.biggerThan(3)

    println

(

10

biggerThan

3

)

}



Runoob 托管在 www.runoob.com

Runoob 托管在 www.runoob.com

true

Limitation Description
Must be a member function or an extension function A top-level function cannot be declared infix
Must have exactly one parameter Two or more parameters cannot be expressed in infix form
The parameter cannot be vararg A variable number of arguments makes the right operand of the infix call indeterminate
The parameter cannot have a default value An infix call must state the right operand explicitly

Infix calls have lower precedence than arithmetic operators and higher than && and ||; when mixing them, adding parentheses is recommended to avoid misreading.


Common questions

The following covers several common questions about functions.

Problem Description
When must I declare the return type Required for a block body whose return type is not Unit; an expression body can be inferred at any visibility
How to choose between default parameters and overloading Prefer default parameters for less code; use overloading only when you need completely different implementation logic
Can named arguments be used on Java methods No, Java bytecode does not retain parameter names by default
Can vararg take a List No, you need to convert it to an array first, e.g. *list.toIntArray()
tailrec has no effect The recursive call must be the last step and must not be inside try/catch/finally