Vitali Plagov
03/16/2022, 1:02 PMval 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.mkrussel
03/16/2022, 1:23 PMsingleOrNull()
and handles the error.
Or possibly add the first error
after find
with some parentheses.Vitali Plagov
03/16/2022, 2:24 PMOr possibly add the firstWhat do you mean by that? Can’t understand how to make it 🤔aftererror
with some parentheses.find
Alex
03/16/2022, 2:25 PMmkrussel
03/16/2022, 2:29 PMval 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
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.ephemient
03/16/2022, 4:10 PMval template = service.getAllTemplates().find { ... }
?: error("no template ...")
val version = template.versions.singleOrNull()
?: error("...")
Vitali Plagov
03/18/2022, 1:35 PM