Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Functions
https://kotlinlang.org/docs/reference/functions.html#function-declarations
Kotlin makes programming fun again so naturally the fun
keyword is used to declare a function 😀.
If we only have one return statement we can transform the function to use only an expression.
We could go one step further and remove the return type as the compiler will be nice enough to infer it for us.
Note: inferring the return type works only for single expression function, the compiler won't try to infer it for functions with block body so overuse single expression function 😁.
If a function doesn't return anything we use the Unit
type :
Named arguments
https://kotlinlang.org/docs/reference/functions.html#named-arguments
When calling a function we can change arguments order by naming them in the call :
fun sub(a: Int, b: Int) = a - b
print(sub(b = 1, a = 2)) // 1
Default arguments
https://kotlinlang.org/docs/reference/functions.html#default-arguments
Never dreamt of assigning default values to some arguments instead of having to define multiple overloading functions ? Guess what ? You can 😀 :
Tip : use
@JvmOverloads
to generate overloading methods for Java code.
Local Functions
https://kotlinlang.org/docs/reference/functions.html#local-functions
You can declare local functions, having access to outer scope :
Extensions
https://kotlinlang.org/docs/reference/extensions.html
It is possible to extend existing classes with new functionalities, even existing JVM classes.
We just need to prefix the function name with the receiver type, followed by .
. The receiver will be accessible as this
in the function.
Infix notation
https://kotlinlang.org/docs/reference/functions.html#infix-notation
Using infix
keyword and extension functions
we can use infix notation for some of our functions :
Vararg
https://kotlinlang.org/docs/reference/functions.html#variable-number-of-arguments-varargs
As in Java we might need to pass a variable number of arguments. In this case we need to prefix the argument by the keyword vararg
:
Operator Overloading
https://kotlinlang.org/docs/reference/operator-overloading.html
At last we can overload common operators using the operator
keyword 😃 :
Tail recursion
https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functions
A tail recursive function can be marked as such with the tailrec
keyword.
Beware: contrary to Scala the compiler won't raise an error if you incorrectly marked a function as tail recursive.