In Java you have a lot of List Functions. e.g: List.size(), List.isEmpty()...
Is it possible to make my own Function like List.nullOrEmpty() and how can i do this?
This will help me a lot.
CodePudding user response:
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 let's say a 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
}
CodePudding user response:
With the function List.isEmpty()
you will check/avoid the NullPointerException.
But to answer your question, yes, you van make your own function.
My question to you is what do you want that function to check? Maybe Java has already a function that does what you want to implement in the function