Kotlin Standard Library Function
In Kotlin, there are different numbers of built-in functions already defined in the standard library and available for use. We can call them by passing arguments according to requirements. In the below program, we will use built-in functions arrayOf(), sum() and println(). The function arrayOf() requires some arguments like integers, double, etc to create an array and we can find the sum of all elements using sum() which does not require any argument.
Below is the implementation of the standard library function:
fun main(args: Array<String>) {
var sum = arrayOf(1,2,3,4,5,6,7,8,9,10).sum()
println("The sum of all the elements of an array is: $sum")
}
Output:
The sum of all the elements of an array is: 55
In below program, we will use rem() to find the remainder.
fun main(args: Array<String>) {
var num1 = 26
var num2 = 3
var result = num1.rem(num2)
println("The remainder when $num1 is divided by $num2 is: $result")
}
Output:
The remainder when 26 is divided by 3 is: 2
The list of different standard library functions and their use :
- sqrt() – Used to calculate the square root of a number.
- print() – Used to print a message to standard output.
- rem() – To find the remainder of one number when divided by another.
- toInt() – To convert a number to integer value.
- readline() – Used for standard input.
- compareTo() – To compare two numbers and return boolean value.
Kotlin functions
In Kotlin, functions are used to encapsulate a piece of behavior that can be executed multiple times. Functions can accept input parameters, return values, and provide a way to encapsulate complex logic into reusable blocks of code.
Learn Kotlin Functions
- What is Functions?
- Example of a Function
- Types of Functions in Kotlin
- 1. Kotlin User-Defined Function
- 2. Kotlin Standard Library Function
- Advantages and Disadvantages in Kotlin Function