-1

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?

i create a class who do this.

public class ListUtil { 
    public static boolean isNullOrEmpty(final List list) { 
        return list == null || list.isEmpty(); 
    }
 } 

but here i need to call ListUtil.isNullOrEmpty(myList) to check.

Shoxious
  • 11
  • 3

2 Answers2

1

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
}
Sergio
  • 27,326
  • 8
  • 128
  • 149
0

With the function List.isEmpty() you will check/avoid the NullPointerException.

But to answer your question, yes, you can 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

Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
JMag
  • 110
  • 2
  • 9