Hello. Can someone explain to me a small moment in the correspondence regarding criticism and suggestions of this new switch-on-strings in the 7th package of Toad, in 334 coin project 334 JSR?

I will quote:

Now that we plan to have closures, do we still need strings-in-switch? Won't a string-to-function map be about as fast (though maybe less convenient)? I don't know what the use cases are for strings-in-switch, but the feature already felt a bit low-benefit to me, and seems even more so now with closures. 

source link

What is the concept of closures, and why, if implemented, is the question asked whether there is a need for this switch option? What is the connection between them, explain for non-understanding. And also at the expense of the question whether the string-to-function map will be no less fast.

Can anyone do a little introduction to understand this comment? I will be grateful.

    2 answers 2

    I can be wrong, but it seems to me that we are talking about closures, i.e. lambdas

    An example where switch can be replaced by a lambda function.

     public static String caseOnString(String str) { switch (str) { case "hello": return "world"; case "bye": return "country"; default: return ""; } } public static String mapOnString(String str) { Function<String, String> map = s -> { if (s.equals("hello")) return "world"; if (s.equals("bye")) return "country"; return ""; }; return map.apply(str); } 
    • As such, it is no different from an if-else without lambdas. This is, of course, a variant like @Roman. - Nofate
    • Well, yes, his version is more like the truth - Artem Konovalov

    I think the following was meant: if we have a String str variable String str , instead of

     switch (str) { case "one": System.out.println(1); break; case "two": System.out.println(2); break; default: System.out.println("?"); } 

    offered to write something like this (closures - these are closures, and in the case of java - lambdas, although they are not full closures):

     Map<String, Runnable> switchMap = new HashMap<>(); switchMap.put("one", () -> System.out.println(1)); switchMap.put("two", () -> System.out.println(2)); switchMap.getOrDefault(str, () -> System.out.println("?")).run();