Suppose we had an abstract class with a single abstract method
abstract public class Foo
{
public Foo(){}
abstract protected String bar();
}
and we refactor it to a normal class that accepts a functional object instead
public class Foo
{
final Supplier<String> bar;
public Foo(Supplier<String> bar){ this.bar = bar; }
}
That is all good; we can do
`new Foo( ()->"whatever" )`, no subclassing is needed!
However, what if, for some reason, we do want to subclass Foo?
public class MyFoo extends Foo
{
final int x;
public MyFoo(int x)
{
super( this::bar ); // ERROR! `this` cannot be referenced here
this.x=x;
}
String bar(){ return ""+x; }
}
There is no way to supply a lambda that depends on `this` to the super constructor. Java is very good at forbidding `this` from being accessed before super is constructed.
The only workaround that I can come up with is to let a super constructor to do a downcast of `this` then bind the lambda expression to it
public class MyFoo extends Foo
...
public MyFoo(int x)
{
<MyFoo>super( thiz->thiz::bar );
this.x=x;
}
public class Foo
...
@SuppressWarnings("unchecked")
protected <This> Foo(Function<This,Supplier<String>> barF)
{
this.bar = barF.apply((This)this);
}
Zhong Yu
bayou.io