Stream: hapi
Topic: convert List of IBaseResource to List of Resources
Luca Toldo (Jan 21 2020 at 15:56):
Dear HAPIsts,
I need to generate a List of Resource, from a List of IBaseResource.
(List<Resource>) BundleUtil.toListOfResources(myBundle);
I was expecting it to be compatible with a simple cast since Resource implements IBaseResource ...
Any advice ?
Ian Bacher (Jan 21 2020 at 16:20):
Type erasure basically means that List<Resource>
is not an instance of List<IBaseResource>
, but even if that weren't the case, what you're trying to do would be unsafe as all Resource
s implement IBaseResource
but IBaseResource
s are not necessarily assignable to the Resource
type.
However, I think you can do what you want in a type-safe manner like so (assuming you're using Java 8 or newer):
BundleUtil.toListOfResources(myBundle).stream().filter(Resource.class::isInstance).map(Resource.class::cast).collect( Collectors.toList());
Luca Toldo (Jan 21 2020 at 16:24):
@Ian Bacher thankyou however now I get another error ...
BaseRuntimeElementDefinition cannot be cast to BaseRuntimeElementCompositeDefinition
Ian Bacher (Jan 23 2020 at 15:20):
BaseRuntimeElementDefinition cannot be cast to BaseRuntimeElementCompositeDefinition
Can you provide an example of what you're trying to do when you get this error?
Last updated: Apr 12 2022 at 19:14 UTC