The listOfNotNull
function in Kotlin is used to create a list of non-null elements. This function belongs to the Kotlin standard library and provides a straightforward way to filter out null values from a list initialization.
Table of Contents
- Introduction
listOfNotNull
Function Syntax- Examples
- Basic Usage
- Combining Nullable and Non-Nullable Elements
- Creating a List from a Nullable Collection
- Real-World Use Case
- Conclusion
Introduction
The listOfNotNull
function is a convenient way to create a list while automatically excluding any null values. This is useful for initializing lists where some elements may be null, and you want to ensure that the resulting list contains only non-null elements.
listOfNotNull Function Syntax
The syntax for the listOfNotNull
function is as follows:
fun <T : Any> listOfNotNull(vararg elements: T?): List<T>
Parameters:
elements
: A variable number of elements, which can include null values.
Returns:
- A list containing only the non-null elements from the provided arguments.
Examples
Basic Usage
To demonstrate the basic usage of listOfNotNull
, we will create a list with some null values.
Example
fun main() {
val list = listOfNotNull(1, null, 2, null, 3)
println("List of non-null values: $list")
}
Output:
List of non-null values: [1, 2, 3]
Combining Nullable and Non-Nullable Elements
This example shows how to use listOfNotNull
with a mix of nullable and non-nullable elements.
Example
fun main() {
val name1: String? = "Alice"
val name2: String? = null
val name3: String? = "Bob"
val names = listOfNotNull(name1, name2, name3)
println("List of non-null names: $names")
}
Output:
List of non-null names: [Alice, Bob]
Creating a List from a Nullable Collection
This example demonstrates how to create a list from a collection that may contain null values.
Example
fun main() {
val numbers: List<Int?> = listOf(1, null, 2, null, 3, null)
val nonNullNumbers = listOfNotNull(*numbers.toTypedArray())
println("List of non-null numbers: $nonNullNumbers")
}
Output:
List of non-null numbers: [1, 2, 3]
Real-World Use Case
Filtering User Input
In real-world applications, the listOfNotNull
function can be used to filter user input or data that may contain null values, ensuring that only valid, non-null data is processed.
Example
fun main() {
val userInputs: List<String?> = listOf("Alice", null, "Bob", "", null, "Charlie")
val validInputs = listOfNotNull(*userInputs.toTypedArray()).filter { it.isNotEmpty() }
println("List of valid inputs: $validInputs")
}
Output:
List of valid inputs: [Alice, Bob, Charlie]
Conclusion
The listOfNotNull
function filters out any null values from the provided elements and creates a list containing only the non-null elements. This ensures that the resulting list does not contain any nulls, making it safer to use in situations where null values are not desired.
Comments
Post a Comment
Leave Comment