bodiam
02/18/2021, 11:23 PMval product: Product = products.find { it.name = input } ?: throw IllegalArgumentException("Product $input not found")
I know that it will be very unlikely to not find the product in this list (say, impossible), so, I’d rather not clutter my code with the “if null throw exception” stuff, and rather have find
throw an exception if the product can’t be found, like this:
val product: Product = products.find { it.name = input }
I’d rather not make Product nullable (Product?
), cause that will lead to some if/then elses later in my code. Is there any clean way I’ve missed to accomplish this?Youssef Shoaib [MOD]
02/18/2021, 11:49 PMinline fun <T> Iterable<T>.findOrThrow(
predicate: (T) -> Boolean
): T? = find(predicate) ?: throw IllegalArgumentException("Item not found")
nkiesel
02/18/2021, 11:49 PMval product: Product = products.first { it.name == input }
? That throws a NoSuchElementException though. Or ``val product: Product = checkNotNull(products.find { it.name == input }` but that throws an IllegalStateException.nanodeath
02/19/2021, 12:24 AMrequire
and check
functionsbodiam
02/19/2021, 12:29 AMbodiam
02/19/2021, 12:30 AMfirst
can also take a predicate. Thanks!nkiesel
02/19/2021, 1:33 AMProduct product = products.stream().filter(it -> it.getName().equals(input)).findFirst().orElseThrow(NoSuchElementException::new);
nkiesel
02/19/2021, 1:39 AMProduct product = products.stream().filter(it -> it.getName().equals(input)).findFirst().get();
bodiam
02/19/2021, 1:40 AMVadim Pesochinskiy
03/01/2021, 7:57 PM