Brandon Dixon
Brandon Dixon

Reputation: 1134

Java Lambda Expressions and Object Method Reference

I am currently working on a Java project which will use lambda expressions to update information directly. In this code, Item o will use two lambda expressions, which the object will call at the appropriate time to make calculations. I am using lambda expressions so that I can define a custom function for each item (and would rather not use anonymous objects).

I am running into a problem where I need the lambda function to get information from the object which is executing it (o, in this case). I cannot compile because inside of the function, o.getObjectWidth(), the IDE tells me that 'o may not have been initialized' (which is technically true at this point).

Is there a different way I can include the reference in the lambda expression?

private void addAllItems() {
    Color shipColor = Color.GRAY;
    //draw the bottom oval
    int width = 100;
    int height = 90;
    Item o = new Item("bov","oval",10,true,shipColor,true,Color.black,
            new int[] {0,60,width,height},new int[] {0,0,1,1},
            (Function<Integer,Integer>[]) new Function[]{
                //update by keyboard x
                (n) -> {
                    return DynamicInfo.getKeyboardX()+o.getObjectWidth()/2;
                },
                (n)-> {
                    return DynamicInfo.getKeyboardY()+o.getObjectHeight()/2;
                },
                null,
                null
    });

    allItems.addItem(o);
}

Upvotes: 0

Views: 223

Answers (1)

tsolakp
tsolakp

Reputation: 5948

I think the cleanest approach is to pass Item directly to the function itself along with Integer parameter.

Use BiFunction:

BiFunction<Item, Integer, Integer>

The lambda will look like this:

(i, n) -> {
    return DynamicInfo.getKeyboardX()+i.getObjectWidth()/2;
},
(i, n)-> {
    return DynamicInfo.getKeyboardX()+i.getObjectWidth()/2;
}

And pass reference to itself when calling the function inside the Item:

f.apply(this, 4) 

BTW, why not use List and avoid the ugly cast when creating the array:

Item(...., List< BiFunction<Item, Integer, Integer> > functions, ...)

new Item( ..., Arrays.asList( 
        (i, n) -> {
            return DynamicInfo.getKeyboardX()+i.getObjectWidth()/2;
        },
        (i, n)-> {
            return DynamicInfo.getKeyboardX()+i.getObjectWidth()/2;
        } ), .... );

Upvotes: 1

Related Questions