1

Is it possible to create static inner function using lambda?

Specifically, I want to do the following:

function myFunc(){
    Map<Integer, String> myMap = new HashMap <Integer, String> ();
    myMap.put(1,"A");
    String head = () -> myMap.get(1);
    myMap.put(1,"B");

    System.out.println(head);   // Should print B
}
6
  • What exactly are you trying to do? What's stopping you from calling System.out.println(myMap.get(1))? Commented Mar 9, 2015 at 5:57
  • Nothing. The idea is to be able to re-use the code so I don't have to rewrite it twice. Commented Mar 9, 2015 at 5:58
  • Which code are you trying to reuse? Commented Mar 9, 2015 at 5:58
  • Well in this example, myMap.get(1). But you can imagine any code could go in there. Commented Mar 9, 2015 at 5:59
  • @YongkeBillYu No, we can't imagine it. Your example doesn't demonstrate what you are actually trying to do and doesn't even have type consistency. Commented Mar 9, 2015 at 6:01

1 Answer 1

4

All lambdas are inner functions. The one you wrote is a Supplier<String>:

Supplier<String> getHead = () -> myMap.get(1);
System.out.println(getHead.get());

You can see what types of functions exist by looking through the java.util.function package.

Note however that the standard way to accomplish this (since before lambdas) is simply to write a private method and call it, and the traditional style will have less overhead involved, though whether that overhead is significant is another question.

Sign up to request clarification or add additional context in comments.

4 Comments

It works, although it's not as elegant as I had hoped. Maybe the traditional method is better.
@YongkeBillYu There are times when lambda functions are useful and I don't think this is one of those times. Using them to do Supplier<String> getHead = () -> myMap.get(1); instead of String head = myMap.get(1); seems completely pointless to me, so yes, the "traditional method" would be better in this case.
@JLRishe The point is to call .get() multiple times so that it's like a dynamic variable.
@Saposhiente Yeah, if you Java could implement Properties like in C# then all this could be avoided, alas!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.