Basic Kotlin Tips — 2
Mar 23, 2024
- orEmpty()
The
orEmpty()
method returns an empty string if the value of the invoking input variable isnull
. Otherwise, it returns the input string’s value.
Syntax: fun String?.orEmpty(): String
eg: val strName: String? = "Sachin"
val myName = strName.orEmpty() // similar to - strName ?: ""
2. mapNotNull()
The mapNotNull() function is particularly useful when dealing with collections that may contain null values and we want to avoid null values.
Syntax:
fun <T, R> Collection<T>.mapNotNull(transform: (T) -> R?): List<R>
Example:
val strings = listOf("apple", "android", null, "windows", null)
val nonNullStrings = strings.mapNotNull { it }
println(nonNullStrings) // Output: [apple, android, windows]