Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What am I missing? Java Optional<Long> get returns Object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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:

  1. The type signature for getDuration declares that it returns Optional rather than Optional<Long>.
  2. The type signature for getDuration returns Optional<T> where T is a type declared on the class (so, like Asset<T>), and you’ve declared asset as Asset asset = ... rather than Asset<Long> asset = ....
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading