Proposal: single-expression method bodies

Daniel Trebbien dtrebbien at gmail.com
Sat Nov 25 03:58:36 UTC 2017


Hello Zheka,

I personally like your idea of supporting expression lambda syntax with
methods.  Being able to write simple getters as public int getSomeField()
-> someField; would be very useful, in my opinion.

I don't like the idea of expression lambda syntax support for switch cases,
though, because I think that it wouldn't work well with fall-through
support.  By way of example, consider:

String s = switch (o) {
    case Integer n:
    case Double n:
        return n.toString();
}

(I believe that reusing bound variable names like this is anticipated to be
supported, but I could be wrong.)

Allowing expression lambda syntax with that might look like:

String s = switch (o) {
    case Integer n ->
    case Double n -> n.toString();
}

Or maybe:

String s = switch (o) {
    case Integer n,
    case Double n -> n.toString();
}

Or:

String s = switch (o) {
    case Integer n, Double n -> n.toString();
}

All three seem a bit strange and potentially confusing to me.

Daniel

On Wed, Nov 22, 2017 at 11:24 PM, Zheka Kozlov <orionllmain at gmail.com>
wrote:

> Sorry if I'm repeating what was already discussed before. I didn't find
> anything about this in the old threads.
>
> Currently, lambdas support two forms of bodies:
>
> 1. Function<Integer, String> func = (Integer i) -> i.toString();
> 2. Function<Integer, String> func = (Integer i) -> {
>     return i.toString();
> };
>
> But for methods only the second form is supported:
>
> public String func(Integer i) {
>     return i.toString();
> }
>
> This seems unfair to me, and I think the first form should be supported
> too:
>
> public String func(Integer i) -> i.toString()
>
>
> Single-expression method bodies can reduce the amount of boilerplate:
>
> public static int square(int x) -> x * x
>
> // Simple getter
> public int getSomeField() -> someField;
>
>
> This will also be consistent with the two forms of switch (regular switch
> and expression switch):
>
> switch (o) {
>     case Integer i: return i.toString();
> }
>
> vs.
>
> String s = switch (o) {
>     case Integer i -> i.toString();
> }
>
> What do you think?
>


More information about the amber-dev mailing list