Beyond just functions for manipulating collections, the Kotlin standard library provides many other helpful functions. Let's explore a few examples of how these functions can make our code more concise, readable, and safe.
One such function is isNullOrEmpty(). This provides a convenient way to check whether a collection is either null or empty:
if (list.isNullOrEmpty()) {
// handle empty case
}
This helps us to handle those common edge cases with a standard available function.
If we find that a collection is null, but would rather work with an empty collection than a null one, the Kotlin standard library provides functions to retrieve an empty collection of your choosing:
val emptyList = emptyList<String>()
val emptyMap = emptyMap<String, Int>()
val emptyArray = emptyArray<String>()
This can be done using a nullable collection type as well. We can use the orEmpty() function on a collection to return either the current non-null value or a default empty collection instead:
var possiblyNullList: List<String>? = null
var nonNullList = possiblyNullList.orEmpty()
The Kotlin standard library also provides a variety of convenience functions for working with string types. In particular, there are several functions for checking whether a string is null, blank, or empty:
val string: String? = null
if (string.isNullOrBlank()) {
// handle edge cases
}
if (string.isNullOrEmpty()) {
// handle edge cases
}
if (string?.isEmpty() == true) {
// handle empty string
}
if (string?.isNotBlank() == true) {
// handle non-blank string
}
These are quite useful when working toward eliminating null from your code base as much as possible.
Additionally, the String type has an orEmpty() function that can be used to return the current non-null String value or a default empty String:
var possiblyNullString: String? = null
var nonNullString = possiblyNullString.orEmpty()
The Kotlin standard library provides many helpful functions for working with strings, collections, arrays, numerical types, and more. By leveraging these functions, we can begin to write more functional code with fewer side effects, greater readability, and less code.