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

How can I make this functional programming operation work

How can I make this work? Trying to throw an exception as the default thing to do if the map does not containt the key but editor says "The target type of this expression must be a functional interface":

cliente.setMIMECode(CertificationsConstants.FILE_TYPES.getOrDefault(
    uploadCertificateSchoolRequest.getTypeFile(), 
    () -> { throw new IllegalStateException("unkonwn filetype"); }
));

>Solution :

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

getOrDefaults signature is getOrDefault(K, V), not getOrDefault(K, Supplier<V>). You want to use Map#computeIfAbsent which accepts a Function<? super K, ? extends V> as second argument to compute a value in the case of an absent key.

That said, it feels wrong to (ab)use computeIfAbsent for this. Why not simply check the result, once retrieved from the map?

final var fileType = CertificationsConstants.FILE_TYPES.get(
    uploadCertificateSchoolRequest.getTypeFile();
if (fileType == null) {
  throw new IllegalStateException("unknown filetype");
}
cliente.setMIMECode(fileType);

Or, if you don’t require this exact exception type, the following:

cliente.setMIMECode(
    Objects.requireNonNull(
        CertificationsConstants.FILE_TYPES.get(
            uploadCertificateSchoolRequest.getTypeFile(),
            "unknown filetype")));
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