There are some functions I use so often they may b...
# stdlib
m
There are some functions I use so often they may be useful for the stdlib 🙂
Copy code
val <C : CharSequence> C.nonEmpty
	get() = ifEmpty { null }

val <CollectionType : Collection<*>> CollectionType.nonEmpty
	get() = ifEmpty { null }

val <Element> Array<Element>.nonEmpty
	get() = ifEmpty { null }
Copy code
val actualNonEmptyString = inputString?.nonEmpty ?: error("is required")
val actualNonEmptyList = inputList?.nonEmpty ?: error("is required")
i
So it replaces string/collection with
null
if it's empty? Then you can use
.ifEmpty { null }
instead.
👍 3
m
Thanks, I've updated the definition appropriately. Given that I use it so often I'd still prefer a single property 😄
i
The proposed
notEmpty
extension property name doesn't look as clear as
ifEmpty { null}
1
m
nonEmpty
is clearer than
notEmpty
😁
nullIfEmpty
? 🤔 I really don't like the function call just for the null 😅
a
+1 for using
ifEmpty
but a
ifNullOrEmpty
could be nice. Then again,
isNullOrEmpty
(and blank for strings) exists.
inputString?.takeIf {!it.isNullOrEmpty()} ?: error("required")
Edited my message for the 7th time or something