The minOfOrNull() extension function in Kotlin returns the smallest value among all values produced by the selector function applied to each element in the collection, or null if there are no elements.
The syntax of Set.minOfOrNull() extension function is:
fun <T> Set<T>.minOfOrNull(selector: (T) -> Double): Double?
This minOfOrNull() extension function of Set returns the smallest value among all values produced by selector function applied to each element in the collection or null if there are no elements.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns a Double value to be compared. |
Set.minOfOrNull() returns value of type Double?
.
Using minOfOrNull() to find the minimum value among integers in a set transformed to double, or null if the set is empty.
For example,
fun main() {
val numbers = setOf(3, 1, 4, 1, 5)
val minValue = numbers.minOfOrNull { it.toDouble() }
println(minValue)
}
1.0
Using minOfOrNull() to find the minimum length among strings in a set, or null if the set is empty.
For example,
fun main() {
val strings = setOf("apple", "pear", "banana")
val minLength = strings.minOfOrNull { it.length.toDouble() }
println(minLength)
}
4.0
Using minOfOrNull() to find the minimum age among custom objects in a set, or null if the set is empty.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val minAge = people.minOfOrNull { it.age.toDouble() }
println(minAge)
}
25.0
Using minOfOrNull() to handle an empty set and return null.
For example,
fun main() {
val emptySet = emptySet<Int>()
val minValue = emptySet.minOfOrNull { it.toDouble() }
println(minValue)
}
null
In this Kotlin tutorial, we learned about minOfOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.