Is there any reason why something like `isNotNullO...
# getting-started
c
Is there any reason why something like
isNotNullOrEmpty
doesn't exist by default? I hate having to do
!something.isNullOrEmpty
t
isNotEmpty
is what you're looking for. It also checks for
null
.
c
Oh crap. Thanks @tseisel
l
In this case the function you was looking for is already defined. If it was not, you could have written an "Extension Function" like:
fun CharSequence?.isNotNullOrEmpty() : Boolean = !this.isNullOrEmpty();
this will make it possible to call the function as you wanted to:
fun main(){
var test : String? = null
test.isNullOrEmpty() //true
test.isNotNullOrEmpty() //false
}
Of course it is better to use to build in methods, but for future terms, if you experience similiar problems, this could be an option 🙂
👍 1
c
@Lars Wenning thanks @tseisel question though. When I look at the docs... how would I know that? https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/is-not-empty.html
n
uh...you wouldn't, because
isNotEmpty
doesn't check null. we have
isNotEmpty
and also
isNullOrEmpty
, which, besides the name, you can tell works because it operates on a
Collection<T>?
. (docs) so...you want
!foo.isNullOrEmpty()
. you could make an extension method
isNotNullOrEmpty()
, but IMO it's not necessary; tbh I'm not even sure why we have
isEmpty()
and
isNotEmpty()
. Maybe for concise method references in filters/sequences.
c
@nanodeath I just hate the
!
n
gonna have a rough time programming then
👏 1
c
😃
t
The downside with the
isNotNullOrEmpty
extension function and
.not()
is that you won't benefit from smart casts from
String?
to
String
(unlike
!isNullOrEmpty
)
n
you could use contracts maybe.