https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

08/14/2020, 5:31 AM
Is there any reason why something like
isNotNullOrEmpty
doesn't exist by default? I hate having to do
!something.isNullOrEmpty
t

tseisel

08/14/2020, 6:26 AM
isNotEmpty
is what you're looking for. It also checks for
null
.
c

Colton Idle

08/14/2020, 6:28 AM
Oh crap. Thanks @tseisel
l

Lars Wenning

08/14/2020, 6:58 AM
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

Colton Idle

08/14/2020, 7:02 AM
@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

nanodeath

08/14/2020, 2:06 PM
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

Colton Idle

08/14/2020, 3:08 PM
@nanodeath I just hate the
!
n

nanodeath

08/14/2020, 3:08 PM
gonna have a rough time programming then
👏 1
c

Colton Idle

08/14/2020, 3:08 PM
😃
t

tseisel

08/15/2020, 12:42 PM
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

nanodeath

08/15/2020, 2:59 PM
you could use contracts maybe.
3 Views