Kotlin Array - minOf() Function



The Kotlin array minOf() function is used to return the smallest value among all the elements of an array or collection.

This function takes a selector function and returns the smallest value produced by the selector function.

Syntax

Following is the syntax of Kotlin array minOf() function −

fun <T> Array<out T>.minOf(
   selector: (T) -> Double
): Double

Parameters

This function accepts a selector as a parameter.

Return value

This function returns an element's value, which will be largest value among all value.

Example 1

The following is a basic example to demonstrate the use minOf() function −

fun main(args: Array<String>) {
   var array = arrayOf<Int>(1, 2, 3, 4)
   val m_elem = array.minOf({ it })
   println("The min element is: $m_elem")
}

Output

Following is the output −

The min element is: 1

Example 2

Now, let's create another example. Here, we create an student class. We then use the minOf function to check the smallest age of student array −

data class Student(val age: Int) : Comparable <Student> {
   override fun compareTo(other: Student) = other.age - age
}
fun main(args: Array<String>) {
   val student1 = Student(25)
   val student2 = Student(18)
   val student3 = Student(24)

   var array = arrayOf<Student>(student1, student2, student3)    
   val m_age = array.minOf({it.age})
   
   println("the smallest age is: $m_age")    
}

Output

Following is the output −

the smallest age is: 18

Example 3

The below example uses the minOf function to return the length of the smallest string −

fun main(args: Array<String>) {
   var array = arrayOf<String>("Hello", "tutorialspoint", "India", "Pvt", "ltd")
   val l_length = array.minOf({it.length});
   println("The element having smallest length is: $l_length");
}

Output

Following is the output −

The element having smallest length is: 3
kotlin_arrays.htm
Advertisements