Home > Software engineering >  How can I make this functional programming operation work
How can I make this functional programming operation work

Time:06-07

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"); }
));

CodePudding user response:

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")));
  • Related