# singleOrNull

```kotlin
public fun <T> List<T>.singleOrNull(): T? {
    return if (size == 1) this[0] else null
}


val list = listOf(1, 2, 3, 4, 5)
val singleList = listOf(1)
val emptyList = listOf<Int>()

println(list.singleOrNull())  // null
println(singleList.singleOrNull())  // 1
println(emptyList.singleOrNull())  // null
```

```kotlin
public inline fun <T> Iterable<T>.singleOrNull(predicate: (T) -> Boolean): T? {
    var single: T? = null
    var found = false
    for (element in this) {
        if (predicate(element)) {
            if (found) return null
            single = element
            found = true
        }
    }
    if (!found) return null
    return single
}


val list = listOf(1, 2, 3, 4, 5)
println(list.singleOrNull{ it > 3 })  // null
println(list.singleOrNull{ it > 4 })  // 5
println(list.singleOrNull{ it > 5 })  // null
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gold.gitbook.io/kotlin/collections/elements-operations/singleornull.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
