I have a getter in Java which returns an Optional but when I try to call .get() on it and assign it to a Long as below my compiler and IDE throws an error calling it a type mismatch, claiming it is returning an Object. This seems straight forward, I’ve worked with Optionals in the past and never have had this issue. I’m not sure why it would matter but the asset class implements an interface which has getDuration() as part of it, returning an Optional. Does anyone know what is wrong here (getDuration() returns Optional)?
Edit: Added full implementation with generics to clarify
Long duration = assetResponse.getAsset().getDuration().get();
Response object class:
public class AssetResponse() {
private AssetInterface asset;
public AssetInterface getAsset() {
return asset;
}
}
Interface class:
public interface AssetInterface<T> {
@JsonIgnore
Optional<Long> getDuration();
List<T> getAssetTagList();
}
Implementation class:
public Asset implements AssetInterface<AssetV1> {
private Optional<Long> duration;
private List<AssetV1> assetTags;
@Override
public List<AssetV1> getAssetTagList() {
return assetTags;
}
public setDuration(Optional<Long> duration) {
this.duration = duration;
}
@Override
public Optional<Long> getDuration() {
return duration;
}
}
>Solution :
It’s impossible to know for sure without seeing more code. But I see two plausible ways this could happen:
- The type signature for
getDurationdeclares that it returnsOptionalrather thanOptional<Long>. - The type signature for
getDurationreturnsOptional<T>whereTis a type declared on the class (so, likeAsset<T>), and you’ve declaredassetasAsset asset = ...rather thanAsset<Long> asset = ....