0

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);
}
1
  • Redesign your class to take lambdas with two arguments, so it passes both n and o into calls to the lambda? Commented Jan 29, 2018 at 23:33

1 Answer 1

1

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;
        } ), .... );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is much more elegant and solves the problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.