Search code examples
javainitializer

Can i put a empty return statement inside an instance initializer?


I'm am trying to put a empty return statement inside an instance initializer block to exit in case the string is null but compiler say "Cannot return from within an initializer" , i have found this answer this answer on stack-overflow but it's about "static initializer" and maybe my case is different, this is the code:

lsDestinatari.parallelStream().forEach(o->{
    pushManagerDB.insert("log_notifiche",new HashMap<String, Object>(){{
        String logContent = pushToPlayers(getPlayersFromUser(o,pushManagerDB),content,data,page);
        if(logContent==null)
            return;     
        put("content", logContent);
        //TODO[...]     
    }});
});         

Solution

  • You can't put a return in an initializer: as it says in JLS Sec 8.6:

    It is a compile-time error if a return statement (§14.17) appears anywhere within an instance initializer.

    In this case, you don't need to: just put only in the non-null case:

    if (logContent != null) {
      put("content", logContent);
    }
    

    But note that there's no need to be using an initializer at all. I know that some people think that double-brace initialization is a smart trick; but honestly, it's more trouble than it's worth. You create unnecessary subclasses, potentially enclose references which lead to memory leaks, break serialization etc. All for the sake of "saving" a few lines of code.

    Just build the map outside the insert call:

    String logContent = pushToPlayers(getPlayersFromUser(o,pushManagerDB),content,data,page);
    HashMap<String, Object> map = new HashMap<>();
    if (logContent != null) {
      map.put("content", logContent);
    }
    pushManagerDB.insert("log_notifiche", map);
    

    or

    pushManagerDB.insert(
        "log_notifiche",
        logContent != null
            ? Collections.singletonMap("content", logContent)
            : Collections.emptyMap());