0 votes
in Kotlin by
Explain Functions in Kotlin?

1 Answer

0 votes
by

Functions in any programming language is a group of similar statements which is designated to perform a specific task. Functions allow a program to break it into various small code blocks. This division of code increases the readability of code, reusability of code, and makes a program easy to manage.

As Kotlin is known as a statically typed language. Here, the ‘fun’ keyword is used to declare a function. In Kotlin, there are two types of functions which solely depends upon its availability in the standard library or user definition. They are:

  • Standard library function
  • User-defined function

Kotlin Functions

Kotlin Functions

Now, let us discuss them in detail with Kotlin code examples.

Standard Library Function

They are built-in library functions that can be defined implicitly and available for use.

For Example 2:

fun main(args: Array<String>){  
var number = 9  
var result = Math.sqrt(number.toDouble())  
print("$result")  
}  

Output:

3.0

sqrt() is a function defined in the library which returns the square root of a number.

print() function prints message to a standard output stream.

User-defined Function

As the name suggests, these functions are usually created by users, and they can be used for advanced programming.

Here, functions are declared using the ‘fun’ keyword.

For Example 3:

fun functionName(){
//body of the code
}

Here, we call the function to run codes inside the body functionName()

Kotlin function examples:

fun main(args: Array<String>){  
    sum()  
    print("code after sum")  
}  
fun sum(){  
    var num1 =8  
    var num2 = 9  
    println("sum = "+(num1+num2))  
}  

Output:

sum = 17

code after sum

Related questions

0 votes
asked May 26, 2022 in Kotlin by Robin
0 votes
0 votes
asked May 26, 2022 in Kotlin by Robin
0 votes
0 votes
asked May 26, 2022 in Kotlin by Robin
...