Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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 :
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
Never dreamt of assigning default values to some arguments instead of having to define multiple overloading functions ? Guess what ? You can 😀 :
Tip : use
@JvmOverloadsto generate overloading methods for Java code.
You can declare local functions, having access to outer scope :
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 keyword and
extension functions we can use infix notation for some of our functions :
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
At last we can overload common operators using the
operator keyword 😃 :
A tail recursive function can be marked as such with the
Beware: contrary to Scala the compiler won't raise an error if you incorrectly marked a function as tail recursive.