Function pointer to String method in Java

  • A+

I don't understand a couple of things with lambda.

String s = "Hello World";        Function<Integer, String> f = s::substring; s = null; System.out.println(f.apply(5)); 

Why is the f.apply method still working if s = null. After all, the String object should be deleted by the GC because there is no pointer that points to the object.

One more thing, why don't I need a return statement here?

Function<Integer, String> f = t -> t + ""; 


Let's convert that method reference to a lambda and see what happens:

String s = "Hello World"; Function<Integer, String> f = i -> s.substring(i); // Doesn't compile! s = null; System.out.println(f.apply(5)); 

The above doesn't compile because s is being changed outside of the lambda, so it is not effectively final. Therefore, we can deduce that using a method reference caches the value of s before it's actually used.

See: Is method reference caching a good idea in Java 8?


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: