Getting Started with Kotlin – Tutorial 4 – Functions

Compared to JAVA, Kotlin has a different syntax when writing functions. Lets take a look at an example and then break down every line to understand it.

In kotlin, to define a function you have to use the fun keyword. After the keyword comes the function name and then the parameters.

You also have to provide the type of parameter that the functions accepts. Here message is the parameter name and String is the type.

After the parameters, the return type is provided, here the return type is Int. If you do not want a return type then you can omit this syntax.

 

Now lets look at some more examples to get more familiar with functions in Kotlin.

Function without return type:

Function with more than one parameter:

If your function comprises of a single statement, then you can omit the curly brackets:

Same goes when returning a value from the function:

Providing parameter names when passing values in function

Just like in python, you can also provide names for parameters when calling the function. Lets see from one of the previous examples.

By convention you would call this function like this.

Kotlin provides the ability to specify parameter name.

You can also change the order when using parameter name.

 

Kotlin also provides a new feature called Extension Functions, we will look at them in future tutorials.

 

<< Previous Tutorial “Getting Started with Kotlin – Tutorial 3 – Looping”

Leave a Reply

Your email address will not be published. Required fields are marked *

two × five =