You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the Collection interface. Since Collection extends Iterable, all Collection implementations have access to it—but not all Iterables do. For example, if you have a custom Iterable that doesn’t implement Collection (like a lazy sequence or a handwritten iterator), you can’t call isEmpty() on it, but you can still use none().
  • none() is defined directly on the Iterable interface, 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 standard Collection implementations (e.g., ArrayList, HashSet) track their size internally, so this method just checks if size == 0.
  • The default implementation of no-arg none() for a generic Iterable works 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 the Iterable is actually a Collection, none() will delegate directly to isEmpty() under the hood, so you get the same O(1) performance as calling isEmpty() 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 Collection type (like List or Set), use isEmpty()—it’s more explicit about your intent and guarantees O(1) performance.
  • If you’re dealing with a generic Iterable (like a Sequence or custom iterator), use none() since isEmpty() isn’t available. And remember: for Collection instances, Kotlin optimizes none() to match isEmpty()’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—something isEmpty() can’t do.

内容的提问来源于stack exchange,提问作者Mattias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:26:57