Rob Elliot
03/09/2021, 11:37 AMsingleOrNull
- I assumed it would throw an exception if size > 1, but it returns null.Rob Elliot
03/09/2021, 11:47 AMIterable<T>
has 0..1 elements by returning a T?
or throwing an exception if size > 1.Rob Elliot
03/09/2021, 11:47 AM0
, 1
, 0..1
, 0..*
, 1..*
- it’s not arity…)Timo Gruen
03/09/2021, 12:02 PMTimo Gruen
03/09/2021, 12:03 PMfirst()
for sth. like that. Or i’m simply asserting that the collection size is less-equal 1. But don’t quite understand the reason to choose Collection if you are just having zero or exactly one value(s)?raulraja
03/09/2021, 12:16 PMfun <A> Iterable<A>.firstOrThrow(): A =
if (size > 1) throw IllegalStateException("unexpected size == $size. $this")
else first()
but as @Timo Gruen said maybe if you have a data structure that can only contain a single potentially absent element then nullable types it’s a better option.Rob Elliot
03/09/2021, 12:46 PMYoussef Shoaib [MOD]
03/09/2021, 3:15 PMfun <A> Iterable<A>.singleOrThrow(): A? =
if (size > 1) throw IllegalStateException("unexpected size == $size. $this")
else firstOrNull() // Returns A if size == 1 and null if size == 0
Rob Elliot
03/09/2021, 3:22 PMsingleOrNull(predicate: (T) -> Boolean)
that I was using btw)