Functions in [Kotlin] are declared with the *fun* keyword:
{jet}
fun double(x : Int) : Int {
  return x * 2
}
{jet}

A function call goes in the traditional way:
{jet}
val two = demo(1)
{jet}

See also [Infix calls|#Infix calls] and [Operator overloading].

h3. Single-expression functions

If a function just returns a value of a single expression, one can specify its body after '{{=}}' and with no *return* statement:
{jet}
fun double(x : Int) : Int = x * 2
{jet}

In this case, it is allowed to omit the return type annotation, and the type will be inferred from the expression on the right-hand side:
{jet}
fun double(x : Int) = x * 2
{jet}

{anchor:Unit}

h3. {{Unit}}\-returning functions

If a function does not return any useful value, its return type is {{Unit}}. {{Unit}} is a type of [tuples|Tuples] of zero components, its an alias for {{Tuple0}}. It has only one value -- a tuple of zero components, that is written {{()}}. This value does not have to be returned explicitly:
{jet}
fun printHello(name : String?) : Unit {
  if (name != null)
    print("Hello, $name!")
  else
    print("Hi there!")
  // We don't need to write 'return ()' or 'return', although we could
}
{jet}

Neither has the {{Unit}} return type to be specified explicitly:
If a function has a block body (in curly braces, not after '{{=}}') and returns {{Unit}}, one can omit the return type annotation:
{jet}
fun printHello(name : String?) {
//...
}
{jet}

h3. Local functions

[Kotlin] supports _local functions_, i.e. one can define a function inside a function:
{jet}
fun dfs(graph : Graph){
  fun dfs(current : Vertex, visited : Set<Vertex>) {
    if (!visited.add(current)) return
    for (v in current.neighbors)
      dfs(v, visited)
  }

  dfs(graph.vertices[0], HashSet())
}
{jet}

Local functions can "see" local variables of outer functions (i.e. the closure), so we can have our {{visited}} set as a local variable, not a parameter to always pass around:
{jet}
fun dfs(graph : Graph){
  val visited = HashSet<Vertex>()
  fun dfs(current : Vertex) {
    if (!visited.add(current)) return
    for (v in current.neighbors)
      dfs(v)
  }

  dfs(graph.vertices[0])
}
{jet}

Local functions can even *return* from outer functions using [qualified *return* expressions|Returns and jumps]:
{jet}
fun reachable(from : Vertex, to : Vertex) : Boolean {
  val visited = HashSet<Vertex>()
  fun dfs(current : Vertex) {
    // here we return from the outer function:
    if (current == to) return@reachable true
    // And here -- from local function:
    if (!visited.add(current)) return
    for (v in current.neighbors)
      dfs(v)
  }

  dfs(from)
  return false // if dfs() did not return true already
}
{jet}

h3. Member functions

A _member function_ is a function defined inside a class:
{jet}
class Sample() {
  fun foo() { print("foo") }
}
{jet}

Member functions are called with a dot:
{jet}
Sample().foo() // creates a new object of Sample and calls foo() on it
{jet}
See [Classes and Inheritance].

h3. Generic functions

Functions may have generic parameters which can be specified in angle brackets after the function name and before the value parameters:
{jet}
fun singletonArray<T>(item : T) : Array<T> {
  val result = Array<T>(1)
  result[0] = item
  return result
}
{jet}
More on generic functions can be found on the page dedicated to [generics|Generics#Generic functions].

h3. Varargs

The last argument of a function may be marked with *vararg* annotation:
{jet}
fun asList<T>(<style desc="font-weight:bold; display:inline":>vararg ts : T) : List<T> {
  val result = ArrayList<T>
  for (t in ts) // ts is an Array
    result.add(t)
  return result
}
{jet}

By default, *vararg* creates an array, but this behavior can be customized by providing arguments to the annotation:
{jet}
fun asList<T>(<style desc="font-weight:bold; display:inline":>vararg<ArrayList<T>> ts : T) : List<T> = ts // ts is a List now!
{jet}
The type argument to the *vararg* annotation denotes a _builder_ type. A call to this function is compiled like this:
{jet}
asList(0, 1, 2)
// Compiles to
val list = ArrayList<Int>(3) // 3 is the size of the structure
list.add(0)
list.add(1)
list.add(2)
asList(list.build()) // For ArrayList, build() just returns the list itself
{jet}
So, the *vararg* builder must be a type that has
* A constructor that takes one {{Int}} parameter
* An {{add()}} function
* A {{build()}} function
The type of the *vararg* parameter if the returned type of {{build()}}.

h3. Default arguments

Function parameters may have _default values_, which are used when a corresponding argument is omitted. This allows to reduce the number of overloads, compared to *Java*:
{jet}
// In java.io.InputStream this function has two versions:
fun read(b : Array<Byte>, off : Int = 0, len : Int = -1) {
  val actualLength = if (len == -1) b.length else len
  // ...
}
{jet}

This function may be called in three forms:
{jet}
read(b, off, len)
read(b, off) // len = -1, effectively, b.length
read(b) // off = 0, len = -1
{jet}

h3. Named arguments

When a function has many parameters (and many of them have defaults), it is very convenient to see parameter names at the call site. Consider the following function in:
{jet}
fun reformat(
  str : String,
  normalizeCase : Boolean = true,
  uppercaseFirstLetter : Boolean = true,
  divideByCamelHumps : Boolean = false,
  wordSeparator : Character = ' '
) {
  // ...
}
{jet}
The best-case call site is fine:
{jet}
reformat(str)
{jet}
But what if we want to change the word separator without changing the flags?
{jet}
reformat(str, true, true, false, '_')
{jet}
Without named arguments, a call site is hard to read. To document it, we can provide parameter names for each argument:
{jet}
reformat(str,
    normalizeCase = true,
    uppercaseFirstLetter = true,
    divideByCamelHumps = false,
    wordSeparator = '_'
  )
{jet}
It is better already, but we can improve it: there's no need to specify all the arguments if some of the default values are fine for us:
{jet}
reformat(str, wordSeparator = '_')
{jet}

h3. Infix calls

If a member function (or an [extension function|Extension functions]) takes one parameter, it may be called in _infix form_, i.e. without a dot after receiver and parentheses around the arguments:
{jet}
1 shl 2
// is the same as
1.shl(2)
{jet}
An infix call _must_ have two parameters. One is not allowed to say, e.g. {{print 1}}, because there's nothing on the left of {{print}}.

Infix calls associate to the left, i.e. {{1 foo 2 bar 3}} means {{(1 foo 2) bar 3}}.

For precedence, see [the grammar|Grammar#Precedence].

h3. Extension functions

[Extension functions] allow us to define a function having some type as a receiver:
{jet}
fun Int.abs() : Boolean = if (this >= 0) this else -this
{jet}
This function can be called on any {{Int}} with a dot, as if it were a member function:
{jet}
print(-1.abs())
{jet}

For more details, see [Extension functions].

h3. Higher-order functions

A _higher-order function_ is a function that takes functions as parameters, or returns a function. A good example of such a function is {{lock()}} that takes a lock object and a function, acquires the lock, runs the functions and releases the lock:
{anchor:lock}
{jet}
fun lock<T>(lock : Lock, body : () -> T) : T {
  lock.lock()
  try {
    return body()
  }
  finally {
    lock.unlock();
  }
}
{jet}
Let's examine the code above: {{body}} has a [_function type_|Function literals#Function types]: {{() -> T}}, so it's supposed to be a function that takes no parameters and returns a value of type {{T}}. It is invoked inside the *try* block, while protected by the lock, and its result is returned by the {{lock()}} function.

If we want to call {{lock()}}, we can pass a [_function literal_|Function literals] to it as an argument:
{jet}
val result = lock(lock, { sharedResource.operation() })
{jet}
Function literals are described in details [on this page|Function literals]. Here we only give a superficial description:
* a function literal is always surrounded by curly braces,
* its parameters (if any) are declared before {{->}} (parameter types may be omitted),
* the body goes after {{->}}.
In our case, there are no parameters, and the expression in the curly braces is the function literal body.

There is a convention in [Kotlin] that makes our example look nicer:
* if the _last_ parameter of a function is itself a function, the corresponding _function literal_ may be passed outside the parentheses:
{jet}
lock (lock) {
  sharedResource.operation()
}
{jet}
This makes our code look more like a 'control structure'.

Another example of a higher order function would be {{map()}} (of Map/Reduce):
{jet}
fun <T, R> List<T>.map(transform : (T) -> R) : List<R> {
  val result = ArrayList<R>()
  for (item in this)
    result.add(transform(item))
  return result
}
{jet}
This function can be called as follows:
{jet}
val doubled = ints.map {it -> it * 2}
{jet}
One other convention helps us here:
* if a function literal has only one parameter, its declaration may be omitted (along with the {{->}}) and its name will be {{it}}:
{jet}
ints map {it * 2} // Infix call + Implicit 'it'
{jet}

These conventions allow us to write [LINQ|http://msdn.microsoft.com/en-us/library/bb308959.aspx]\-like expressions:
{jet}
strings filter {it.length == 5} sortby {it} map {it.toUpperCase()}
{jet}

h4. Extension function literals

Like named extension functions, function literals may declare _receiver parameters_. This allows us to write things like [Groovy-style builders|http://groovy.codehaus.org/Builders] in a type-safe way.

Learn more [here|Function literals#Extensions] and [here|Type-safe Groovy-style builders].

h3. Inline functions

Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a _closure_, i.e. those variables that are accessed in the body of the function. Memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead.

But it appears that in many cases this kind of overhead can be eliminated by _inlining_ the function literals. The functions shown above are good examples of this situation. I.e., the [{{lock()}}|#lock] function could be easily inlined at call-sites. Consider the following case:
{jet}
lock(l) {foo()}
{jet}
Instead of creating a function object for the parameter and generating a call, the compiler could emit the following code:
{jet}
lock.lock()
try {
  foo()
}
finally {
  lock.unlock()
}
{jet}
Isn't it what we wanted from the very beginning?

To make the compiler do this, one needs to annotate the {{lock()}} function with the *inline* annotation:
{jet}
inline fun lock<T>(lock : Lock, body : () -> T) : T {
  // ...
}
{jet}

Inlining may cause the generated code to grow, but if we do it in a reasonable way (do not inline big functions) it will pay off in performance, especially at "megamorphic" call-sites inside loops.

{note:title=Inline functions are not implemented yet}See the corresponding [issue|http://youtrack.jetbrains.com/issue/KT-1434].{note}

h3. Returning many things from a function

Sometimes we need to return several things from a function. Some languages support this through [*out*\-parameters|http://msdn.microsoft.com/en-us/library/aa645764(v=vs.71).aspx], and some -- through _tuples_. We follow the latter way.

Tuples are described in detail on [this page|Tuples]. Here we just give an example:
{jet}
fun splitEmail(email : String) : #(username : String, host : String) {
  return #(email.substringUntil("@"), email.substringAfter("@"))
}
{jet}

h3. What's next

* [Operator overloading]
* [Extension functions]
* [Function literals]
* [Type-safe Groovy-style builders]