Basic Kotlin Tips — 2

Sachin Shelar
Mar 23, 2024

--

  1. orEmpty()

The orEmpty() method returns an empty string if the value of the invoking input variable is null. 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]

--

--

Sachin Shelar
Sachin Shelar

Written by Sachin Shelar

Android | iOS | Flutter | React Native

No responses yet