Method Reference vs Lambda Expression

18 views
Skip to first unread message

zhong...@gmail.com

unread,
Oct 10, 2015, 9:37:29 AM10/10/15
to java.lang.fans
In most cases, a method reference on a variable

    var::foo

is equivalent to a lambda expression

    (params)->var.foo(params)

However, that is not always the case.

## Effective Final

In the lambda expression, `var` is required to be effectively final; but there's no such requirement on `var::foo`.

see also http://stackoverflow.com/q/33052917/2158288

## null

If `var` is null, `var::foo` immediately causes NullPointerExpression. The lambda expression will not; NullPointerExpression is only thrown when the lambda body is invoked.

## static

This is a little silly; but if `foo` is static, `var.foo(params)` is allowed, and `var::foo` is no allowed.


##
I'm sure there's more...

Zhong Yu
bayou.io

Zhong Yu

unread,
Nov 3, 2015, 4:48:43 PM11/3/15
to java.lang.fans
Return statements in lambda body need to be consistent w.r.t to `void`

    void execute(Runnable command) {}

    String f(){ return ""; }

    void test()
    {
        execute( ()->{ return ""; } );  // error, returns a value instead of `void`

        execute( this::f );  // OK

        execute( ()->f() );  // OK

    }



Reply all
Reply to author
Forward
0 new messages