There is already isNullOrEmpty
function in Kotlin for Collections. It is defined like the following:
@SinceKotlin("1.3")
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies (this@isNullOrEmpty != null)
}
return this == null || this.isEmpty()
}
So if you have an object of type List?
you can use it like the following:
val list: List<String>? = ... // somehow get the list
if (list.isNullOrEmpty()) {
// do something when the list is null or empty
}
If you want to create your own function for the List
object in Kotlin you can create an extension function on List
type:
fun <T> List<T>?.hasAtLeastTwoElements(): Boolean = this != null && size >= 2
And then you can use it:
val list: List<String>? = ... // somehow get the list
if (list.hasAtLeastTwoElements()) {
// do something when the list has at least two elements
}