In Kotlin (Android project), which is preferable to use ?
isNullOrEmpty or TextUtils.isEmpty and why
I believe they do the exact thing and are "null" safe, right ?
In Kotlin (Android project), which is preferable to use ?
isNullOrEmpty or TextUtils.isEmpty and why
I believe they do the exact thing and are "null" safe, right ?
Based off of my question here
If your project will be ported to other frameworks, making use of isNullOrEmpty will probably result in a safer experience, because it's based on Kotlin (specifically package kotlin.text) and not on package android.text;
Why is this safer ?
Well, the implementation of isNullOrEmpty might change depending on the platform but it will be available to use and is part of Kotlin, compared to TextUtils.isEmpty being only for android.
I would say isNullOrEmpty is slightly preferable, because it's a language's feature. TextUtils.isEmpty is a library function, external to Kotlin.
For string.isEmpty(), a null string value will throw a NullPointerException Incase of isNullOrEmpty it will check first value is null or not and it will proceed for the empty check. isNullOrEmpty is preferable
The code for TextUtils.isEmpty:
public static boolean isEmpty(@Nullable CharSequence str) {
return str == null || str.length() == 0;
}
The code for isNullOrEmpty:
public inline fun CharSequence?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies (this@isNullOrEmpty != null)
}
return this == null || this.length == 0
}
Witch is basically the same, the inline function also has a contract that will tell the compiler to return false if the value is not null, not sure what the actual usage is, maybe it's an optimization.
Yes , the only difference is NullPointerException.
In isNullOrEmpty first it will check string is null or not .if it is not null then it will check it is check string is empty or not . If any of the condition will true then method will return true.
In TextUtils.isEmpty it check string is empty or not .If string is null then it will throw NullPointerException and your app will crash .
TextUtils.isEmpty is basically the same thing with isNullOrEmpty(). Yet, there are differences in terms of availability and compilation:
1) TextUtils.isEmpty is available from the android.text package, available with Android SDK, and isNullOrEmpty() requires Koltin dependency (kotlin.text package).
2) Another difference is that isNullOrEmpty() is an inline extension function and it is compiled differently, perhaps with a slight performance boost.
Apart from these, there is another useful inline function
isNullOrBlank(). It also returns true if the String contains only white spaces.
In Kotlin isNullOrEmpty is preferable. TextUtils.isEmpty is specific to Java. Both returns boolean if string is empty or null.