Kotlin Functions Types With Examples

Function is a group of statements that perform some task. Functions are used in programming to break code in small modules to reuse the code. Function is declared using fun keyword in kotlin language.

In this article, You will learn how to create and call functions in kotlin programming language.

There are basic two types of functions in Kotlin:

  1. Standard Library Functions
  2. User Defined Functions

Standard Library Kotlin Functions

Standard library functions are native functions in kotlin language which are always available for use. This functions can be called by using arguments in kotlin language.
For Example:
fun main(args: Array<string>) {
     var number = 2.5
     var result = Math.sqrt(number.toDouble())


User Defined Functions

User defined functions are created by user. First we need to define this type of functions before call them, I already mentioned that functions are declared by fun keyword in kotlin. Then We need to give name of the function to identify it from various functions.
fun nameoffunction() {
     // function body
fun main(args: Array<string>) {
For Example:
fun multiplyNumbers(){
     var num1 = 5
     var num2 = 6
     println(“Result = “+ (num1*num2))

fun main(args: Array<string>) {


Parameterized Functions

Parameters are defined using pascal notation like name of parameter: its type in kotlin. Parameters which are defined in function are called formal parameters. Parameters which are used at call of function are called actual parameters. Parameters in function are separated by comma.
For Example:
fun player(name: String, age: Int, club_name: String) {
     println(“Player name is : $name”)
     println(“Player’s age is : $age”)
     println(“Player’s club is : $club_name”)
fun main(args: Array<string>) {
     val playerName = “Cristiano Ronaldo”
     val playerAge = 35
     val playerClub = “Juventus”
     player(playerName, playerAge, playerClub)

Here name, age, club_name are formal parameters and playerName, playerAge, playerClub are actual parameters.

Function with return value
fun player(name: String, age: Int, club_name: String) : String {
     val playerInfo = “Player name is : $name ” + “Player’s age is : $age ” + “Player’s club is : $club_name”
     return playerInfo

fun main(args: Array<string>) {
     val info = player(“Cristiano Ronaldo”, 35, “Juventus”)


Leave a Reply