Kotlin Array - maxOf() Function



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

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

Syntax

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

fun <T> Array<out T>.maxOf(
   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 maxOf() function −

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

Output

Following is the output −

The largest element is: 4

Example 2

Now, let's create another example. Here, we create an student class. We then use the maxOf function to check the largest 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 l_age = array.maxOf({it.age})
   
   println("the largest age is: $l_age")    
}

Output

Following is the output −

the largest age is: 25

Example 3

The below example uses the maxOf function to return the length of the largest string −

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

Output

Following is the output −

The element having largest length is: 14
kotlin_arrays.htm
Advertisements