Shawn
04/29/2024, 11:44 PMfun isEmptyCollection(any: Any): Boolean = when(any) {
is Collection<*> -> any.isEmpty()
is Map<*, *> -> any.isEmpty()
else -> false
}
smart-casting doesn't seem to recognize union types (or at least, support calling methods with identical signatures on a union instance)Shawn
04/29/2024, 11:48 PMfun Any.isEmptyCollection() = when(this) {
is Collection<*> -> isEmpty()
is Map<*, *> -> isEmpty()
else -> false
}
Szymon Jeziorski
04/30/2024, 6:30 AMAny
.
That being said, is there a reason you need parameter to be of Any
type? Do you have some generic functionality that works on both collections and maps and passed object's type is not know in compile-time? Would that be just some private helper function? (wider context would be helpful)Shawn
04/30/2024, 3:42 PMAny
until you cast them, and cass supports a few different column data types, so at this level, there really isn't much type data known ahead of timemohsenoid
04/30/2024, 6:39 PMfun isEmptyCollection(any: Any): Boolean = (any as? Collection<*> ?: any as? Map<*, *>)?.isEmpty() ?: false
However, I personally prefer having a when expression cause it is easier to read and understand.CLOVIS
04/30/2024, 7:17 PMmohsenoid
04/30/2024, 7:17 PMKlitos Kyriacou
05/01/2024, 11:41 AMCLOVIS
05/01/2024, 11:42 AM(yourAny as? Iterable<*>)?.isEmpty() ?: false
Klitos Kyriacou
05/01/2024, 11:44 AMIterable
doesn't implement isEmpty
, and I therefore deleted that sentence from my previous post.CLOVIS
05/01/2024, 11:45 AM(yourAny as? Iterable<*>)?.iterator()?.hasNext() != true
Shawn
05/01/2024, 4:42 PMas?
and the cost of .iterator()
would be like, or at least, whether it would be worth it over the when
CLOVIS
05/01/2024, 4:43 PMShawn
05/01/2024, 4:45 PMCLOVIS
05/01/2024, 4:45 PMis
check on an interface. Everything else I believe is virtually free. But sealed interface
was introduced to the language, and it's meant to be used like this, so…Klitos Kyriacou
05/01/2024, 4:49 PMiterator().hasNext()
is more expensive than isEmpty()
CLOVIS
05/01/2024, 4:51 PMiterator.hasNext()
and isEmpty()
, but fair, in the grand scheme of things it could happen.
However, I believe OP wanted to call this on the return value of a DB driver to parse the values, so this isn't a risk in this case.Shawn
05/01/2024, 4:56 PM