PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] How can I make this functional programming operation work

 November 05, 2022     java, lambda     No comments   

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

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


Answered By - knittl
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing