Kotlin is the officially recommended programming language to develop native Android apps. In this Kotlin tutorial, let’s check how to create functions in Kotlin.
Basic Function
Kotlin uses the fun keyword to define a function. The name of the function is usually written in camel case.
fun codeExample() {
println("hello")
}
You can call the above function as given below.
codeExample()
Function with Returns
You have to specify the data type when you return something through the function. See the example function given below.
fun codeExample(): String {
return "hello"
}
Function with Single Parameter
Parameters are input to the functions. You have to specify the data type of parameter while creating the function.
fun codeExample(name: String): String {
return "hello $name"
}
Function with Multiple Parameters
fun codeExample(name: String, age: Int): String {
return "hello $name you are $age years old"
}
Function with Default Arguments
You can add default arguments to your function as follows.
fun codeExample(name: String = "Ravi", age: Int): String {
return "hello $name you are $age years old"
}
That’s it! That’s how you create functions in Kotlin. I hope this basic Kotlin tutorial will be helpful for you.