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.
1 2 3 4 5 6 |
//Function Example fun simpleFunction(message: String): Int { println(message) return 10 } |
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:
1 2 3 4 5 |
//Function Example fun simpleFunction(message: String) { println(message) } |
Function with more than one parameter:
1 2 3 4 5 |
//Function Example fun printDetails(name: String, age: Int, dob: Date) { println("Name: $name, Age: $age, DOB: ${dob.toString()}") } |
If your function comprises of a single statement, then you can omit the curly brackets:
1 2 3 |
//Function example fun doSomething() = println("Hello World") |
Same goes when returning a value from the function:
1 2 3 |
//Function Example fun multiply(x: Int, y: Int): Int = x * y |
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.
1 2 3 4 5 |
//Function Example fun printDetails(name: String, age: Int, dob: Date) { println("Name: $name, Age: $age, DOB: ${dob.toString()}") } |
By convention you would call this function like this.
1 2 3 |
//Function Example printDetails("Sam", 12, Date()) |
Kotlin provides the ability to specify parameter name.
1 2 3 |
//Function Example printDetails(name = "Same", age = 12, dob = Date()) |
You can also change the order when using parameter name.
1 2 3 |
//Function Example printDetails(age = 12, dob = Date(), name = "Sam") |
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”
2 Comments
Gagan · October 13, 2017 at 10:56 am
I don’t know why Kotlin. But now everyone want to learn this language because this is official language of android development. I have finish java. Now i want to learn Kotlin i search many website to learn this language. But your kotlin tutorial “ good you explained very nicely. After basic i will movie on advance. Thanks.
More about functions in Kotlin - TheTechnoCafe · October 23, 2017 at 7:13 pm
[…] If you are completely new to functions in Kotlin, then please read this: Getting Started with Kotlin – Tutorial 4 – Functions […]