Kotlin标准库中isEmpty()与none()函数是否存在差异?
Kotlin:
isEmpty() vs No-Arg none() - What's the Difference? Great question! Let’s unpack the similarities and subtle differences between these two utility functions in Kotlin.
Core Functional Similarity
First off: for any Collection implementation (like List, Set, etc.), calling isEmpty() and the no-arg none() will give you the same result when checking if the structure has no elements. Both return true only when there are zero elements in the collection.
Key Differences to Note
1. Interface Hierarchy & Availability
isEmpty()is a method defined on theCollectioninterface. SinceCollectionextendsIterable, allCollectionimplementations have access to it—but not allIterables do. For example, if you have a customIterablethat doesn’t implementCollection(like a lazy sequence or a handwritten iterator), you can’t callisEmpty()on it, but you can still usenone().none()is defined directly on theIterableinterface, so it’s universally available across all iterable types in Kotlin.
2. Performance & Implementation Logic
Collection.isEmpty()almost always runs in O(1) time. Most standardCollectionimplementations (e.g.,ArrayList,HashSet) track their size internally, so this method just checks ifsize == 0.- The default implementation of no-arg
none()for a genericIterableworks by iterating through elements until it finds one that exists—this is O(n) in the worst case (when the iterable is empty or has no matching elements). However, Kotlin has an optimization: if theIterableis actually aCollection,none()will delegate directly toisEmpty()under the hood, so you get the same O(1) performance as callingisEmpty()directly.
3. Handling null Elements
Neither method treats a collection containing null elements as "empty". For example:
val listWithNull = listOf(null) println(listWithNull.isEmpty()) // false println(listWithNull.none()) // false
Both check for the presence of elements, not whether elements are non-null. Only a completely empty collection (size = 0) will return true for both.
Usage Recommendations
- If you’re working with a
Collectiontype (likeListorSet), useisEmpty()—it’s more explicit about your intent and guarantees O(1) performance. - If you’re dealing with a generic
Iterable(like aSequenceor custom iterator), usenone()sinceisEmpty()isn’t available. And remember: forCollectioninstances, Kotlin optimizesnone()to matchisEmpty()’s performance. - Also keep in mind that
none()has an overloaded version that takes a predicate (e.g.,myList.none { it > 10 }), which is a powerful tool for checking if no elements meet a condition—somethingisEmpty()can’t do.
内容的提问来源于stack exchange,提问作者Mattias
相关产品推荐
相关产品推荐

