-4

How would be the right way to do something like this in Java:

String a = "abc" + () -> { return "def";};

I understand the above code have no purpose, but it represents my real problem.

EDIT

first post here, intent to get and provide some help ;)

I'm actually trying to concatenate the return value of the function

yshavit - Keeping in mind that a function the value it produces are separate concepts -- and if they weren't, you wouldn't need two constructs for them

many thanks, i didn't really understood that

The real problem is that I don't (or shouldn't) need to write a method "b" for returning this string because it will be executed only once every time method "a" is called. Also it will not even take parameters.

Below is the real code, to help understanding:

    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
    final Connection connection;
    final Statement statement;
    final ResultSet result;
    final ResultSetMetaData meta;
    final int cols;
    final String[] labels;
    final HttpSession session = request.getSession(false);
    final String table = request.getParameter("table");
    
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(
            "<!DOCTYPE html>"
            + "<html>"
            + element("header.html")
            + "<body>"
                + "<nav class=\"sidepane\">"
                    + element("nav_hub.html")
                    //---------------------------------------------------here
                    + () -> { //where i'm trying to concatenate
                        try {
                                    Class.forName("com.mysql.jdbc.Driver");
                                    connection = (Connection) session.getAttribute("connection");
                                    statement = connection.createStatement();
                                    result = statement.executeQuery("SELECT * FROM " + table);
                                    meta = result.getMetaData();
                                    cols = meta.getColumnCount();
                                    labels = new String[cols];

                                    // ESCREVE A TABELA
                                    writer.write("<thead><tr>"); //header
                                    for (int i = 0; i < cols; i++) {
                                        labels[i] = meta.getColumnLabel(i + 1);
                                        writer.write("<th>" + labels[i].toUpperCase() + "</th>");
                                    }
                                    writer.write("</tr></thead><tbody>"); //body
                                    while (result.next()) {
                                        writer.write("<tr>");
                                        for (String column : labels) {
                                            writer.write("<td");
                                            if (meta.isWritable(1)) {writer.write(" contenteditable='true' ");}
                                            writer.write(">" + result.getString(column) + "</td>");
                                        }
                                        writer.write("</tr>");
                                    }
                                    writer.write("</tbody>");
                                } catch (SQLException | ClassNotFoundException e) {
                                    writer.write("erro ao ler banco de dados: " + e.getMessage());
                                }
                    }
                    //--------------------------------------------------------
                + "</nav>"
            + "</body>"
            + "</html>"
    );

}

Now, with yshavit answer I understood that I can't use the lambda as the returned value. Still I don't know how would I use the return of that lambda and concatenate to the other strings (without creating a method).

Obs.: if you're wondering, there is a reason for not using a jsp.

Community
  • 1
  • 1
Lucas Noetzold
  • 1,670
  • 1
  • 13
  • 29
  • Possible duplicate of [How do I concatenate two strings in Java?](https://stackoverflow.com/questions/3753869/how-do-i-concatenate-two-strings-in-java) – Jonas Sep 06 '17 at 14:28
  • But you just can't do that. We have seen what you have tried so far. Why don't you show us your "real problem" now? – Juan Carlos Mendoza Sep 06 '17 at 14:29
  • 1
    Actually your real problem isn't clear at all. – Mena Sep 06 '17 at 14:29
  • What would you expect the answer to be? What is the concatenation of a string `"abc"` and a function? (Keeping in mind that a function the value it produces are separate concepts -- and if they weren't, you wouldn't need two constructs for them.) – yshavit Sep 06 '17 at 14:33
  • Ok so you can't write it that way. For a good recommendation, try showing more information about your real problem. – Patrick Parker Sep 06 '17 at 14:36
  • not a duplicate, fixed with the full problem (wich is a quite ugly code) – Lucas Noetzold Sep 06 '17 at 15:29
  • What you're trying to do isn't easy/natural to do in Java. You're basically trying to write an expression which creates and immediately invokes a method, basically as a way of grouping a bunch of statements together (and also providing an enclosed scope) to get a single value. It's not an unreasonable thing, and in JavaScript it'd be possible (and I think it's even considered decent style, though I'm not sure about that). But Java isn't set up for that. Your best option would be to create a real, non-lambda function for that try block. (Bonus: it'll be less indented, so easier to read.) – yshavit Sep 06 '17 at 15:57
  • Yep, that's it. My intent to do that was more for a convenience. Well if it isn't possible I'll create a method. That basically solver my question, many thanks!! – Lucas Noetzold Sep 06 '17 at 16:29

2 Answers2

-1

A lambda has to rely on a functional interface.
It is a short way to provide an implementation for the single no abstract method of this functional interface.

So you cannot use in this way.

If you have for example a method that takes as parameter the Supplier functional interface, you could invoke it by passing this lambda :

public static void main(String[] args) {
   String a = "abc" + supply(() -> { return "def";});
}

private static String supply(Supplier<String> supplier) {
   return supplier.get();
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
-1

yshavit:

What you're trying to do isn't easy/natural to do in Java. You're basically trying to write an expression which creates and immediately invokes a method, basically as a way of grouping a bunch of statements together (and also providing an enclosed scope) to get a single value. It's not an unreasonable thing, and in JavaScript it'd be possible (and I think it's even considered decent style, though I'm not sure about that). But Java isn't set up for that. Your best option would be to create a real, non-lambda function for that try block. (Bonus: it'll be less indented, so easier to read.)

solves my question

Lucas Noetzold
  • 1,670
  • 1
  • 13
  • 29