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

Vitali Plagov

03/16/2022, 1:02 PM
Hi. I have the following code
Copy code
val version = service.getAllTemplates()
  .find { ... }
  ?.versions // returns a list
  ?.single()
  ?: error("no template found matching the given predicate")
I’m using the
find{}
on purpose so I could handle its failure with a proper error message, I want to do the same with
single()
. I want to throw an exception with my own error message if the list contains more than one element. I tried
singleOrNull()
but still can’t provide a separate error message for it. Looks like the last
error(…)
handles both nulls.
m

mkrussel

03/16/2022, 1:23 PM
You could add an extension method that calls
singleOrNull()
and handles the error. Or possibly add the first
error
after
find
with some parentheses.
v

Vitali Plagov

03/16/2022, 2:24 PM
Or possibly add the first
error
after
find
with some parentheses.
What do you mean by that? Can’t understand how to make it 🤔
a

Alex

03/16/2022, 2:25 PM
You could try getOrElse()
m

mkrussel

03/16/2022, 2:29 PM
Copy code
val version = (service.getAllTemplates().find { ... } ?: error("no template found matching that given predicate")
  .versions // returns a list
  .singleOrNull()
  ?: error("no template found matching the given predicate")
But I would probably go with
Copy code
val template = service.getAllTemplates().find { } ?: error("no template found matching that given predicate")
val version = template
  .versions // returns a list
  .singleOrNull()
  ?: error("no template found matching the given predicate")
Something like that, I haven't tested it.
getOrElse
is probably also a useful solution.
But in general putting the error by where the error happens is easier to understand.
e

ephemient

03/16/2022, 4:10 PM
IMO the clearest thing to do would be to split out the separate error cases, e.g.
Copy code
val template = service.getAllTemplates().find { ... }
    ?: error("no template ...")
val version = template.versions.singleOrNull()
    ?: error("...")
3
v

Vitali Plagov

03/18/2022, 1:35 PM
Thank you all! I think splitting is a good option. I will go with it
4 Views