Issue
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
getOrDefault
s 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")));
Answered By - knittl Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.