Hi. I have the following code ```val version = ser...
# getting-started
v
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
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
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
You could try getOrElse()
m
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
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
Thank you all! I think splitting is a good option. I will go with it