Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access object from lambda passed in object's constructor

I have a Java class MyClass with this constructor:

public MyClass(Consumer<?> someMethod)

And I would like to do that:

final MyClass myObject = new MyClass(obj -> { 
    doSomethingOutsideTheContextOfMyObject();
    myObject.doSmomething(obj);
    });

But I get an compiler error that variable myObject might not be initialized.

According to my research I cannot switch of the compiler showing the error and I cannot fake-initialize the variable as it has to be final. What shall I do?

like image 302
Walter Avatar asked Apr 02 '26 03:04

Walter


1 Answers

Here:

final MyClass myObject

declares a new object myObject. And then you go on:

  = new MyClass(obj -> { 
  doSomethingOutsideTheContextOfMyObject();
  myObject.doSmomething(obj);

using the very same myObject within its own declaration!

That isn't possible like that! You are creating a "self-reference" in circular ways!

like image 183
GhostCat Avatar answered Apr 08 '26 04:04

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!