r/java Sep 19 '18

JEP draft: Concise Method Bodies

http://openjdk.java.net/jeps/8209434
61 Upvotes

51 comments sorted by

View all comments

2

u/jhg023123 Sep 19 '18

Why both = and ->?

11

u/dpash Sep 19 '18

Because they do different things. = is saying that the method is the same as the method handle, and will return what ever the original method returns. -> would return a method handle (and ignore the parameter).

public boolean isEmpty(String s) = String::isEmpty;
public Predicate<String> isEmpty(String s) -> String::isEmpty; 

Does that make sense?

2

u/jhg023123 Sep 19 '18

Oh, I never thought about it like that. Thanks!

0

u/duhace Sep 20 '18

the second example should do like scala instead

 //Predicate[String] == String => Boolean in scala
 def isEmpty: String => Boolean = String.isEmpty _

i'm not sure why the parameter s is even there if it's being ignored

1

u/dpash Sep 20 '18

Because using -> is the wrong thing to use in that situation.

1

u/duhace Sep 20 '18

I'm not sure I'm getting the difference then. In my code, i'm doing the equivalent of returning the method handle as you said, not using the isEmpty method as the implementation like 1.

1

u/dpash Sep 20 '18

Of my two examples, the second is almost certainly a mistake, and you'd normally never write that. In particular because it ignores the parameter, making the method confusing for any users.

1

u/duhace Sep 20 '18

would you post what you would write to clear things up for me? thanks in advance

1

u/lukaseder Sep 20 '18

Important to note also that specific syntax is probably not set in stone at this moment.