What is the none method of the HashSet in Kotlin?
Overview
In Kotlin, the none method of HashSet is used to check two separate operations:
- To check if a
Setis empty. - To check if no element in a
Setmatches the given condition.
Syntax
This method has two syntaxes.
- To check if the
Setis empty:
fun <T> Iterable<T>.none(): Boolean
-
Arguments: This method doesn’t take any argument.
-
Return value: This method returns
trueif theSetis empty.
- Check if no element in the
Setmatches the given condition:
fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean
-
Arguments: This method takes a
as an argument.predicate function Predicate is a functional interface that takes one argument and returns either true or false based on the condition defined. -
Return value: This method returns
trueif no element in theSetmatches the given condition.
Example
The code below demonstrates how to use the none method.
fun main() {//create a new HashSet which can have integer type as elementsvar set: HashSet<Int> = hashSetOf<Int>()println("\nThe set is : $set")// use none method to check if the set is emptyprintln("set.none : ${set.none()}")// add two entriesset.add(1)set.add(2)println("\nThe set is : $set")var isAllKeysLessThanTwo = set.none( { it > 3 } )println("Checking if all elements of the set is less than 3 : ${isAllKeysLessThanTwo}")set.add(4)println("\nThe set is : $set")isAllKeysLessThanTwo = set.none( { it > 3 } )println("Checking if all elements of the set is less than 3 : ${isAllKeysLessThanTwo}")}
Explanation
-
Line 3: We create a new
HashSetobject with the nameset. We’ve used thehashSetOfmethod to create an emptyHashSet. -
Line 7: We use the
nonemethod to check if thesetis empty. In our case, thesetis empty, sotrueis returned. -
Lines 9 and 10: We use the
add()method to add two new elements(_1,2_)to theset. -
Line 13: We use the
nonemethod with a predicate function. The predicate function returnstrueif the element is greater than3. In our case, there is no element is greater than3. So, the predicate fails for all entries and it returnstrue. -
Line 16: We use the
add()method to add a new element4to theset. Now thesetis[1, 2, 4]. -
Line 18: We use the
nonemethod again with the same predicate function. There is one element4that is greater than3. The predicate returnstruefor that element. Therefore, thenonemethod will returnfalse.