title: Lambda this reference in java
body: <p>I want to convert an anonymous class to a lambda expression. But this anonymous class uses the <code>this</code> keyword.</p>
  <p>For example, I wrote this simple Observer/Observable pattern:</p>
  <pre><code>import java.util.ArrayList;
  import java.util.Collection;
  
  public static class Observable {
      private final Collection&lt;Observer&gt; notifiables = new ArrayList&lt;&gt;();
  
      public Observable() { }
  
      public void addObserver(Observer notifiable) { notifiables.add(notifiable); }
      public void removeObserver(Observer notifiable) { notifiables.add(notifiable); }
  
      public void change() {
          notifiables.forEach(notifiable -&gt; notifiable.changed(this));
      }
  }
  
  public interface Observer {
      void changed(Observable notifier);
  }
  </code></pre>
  <p>and this sample code with an anonymous class (use the this keyword):</p>
  <pre><code>public class Main {
  
      public static void main(String[] args) {
          Observable observable = new Observable();
          observable.addObserver(new Observer() {
              @Override
              public void changed(Observable notifier) {
                  notifier.removeObserver(this);
              }
          });
          observable.change();
      }
  }
  </code></pre>
  <p>but when I convert it to a lambda expression:</p>
  <pre><code>public class Main {
  
      public static void main(String[] args) {
          Observable observable = new Observable();
          observable.addObserver(notifier -&gt; { notifier.removeObserver(this); });
          observable.change();
      }
  }
  </code></pre>
  <p>I get this compilation error:</p>
  <pre><code>Cannot use this in a static context and in a non `static` context
  
  
  
  public class Main {
      public void main(String[] args) {
          method();
      }
  
      private void method() {
          Observable observable = new Observable();
          observable.addObserver(notifier -&gt; {
                  notifier.removeObserver(this);
          });
          observable.change();
      }
  }
  </code></pre>
  <p>The compilation error is:</p>
  <pre><code>The method removeObserver(Main.Observer) in the type Main.Observable is not applicable for the arguments (Main)
  </code></pre>
  <p>Is there a way to reference the lambda object with <code>this</code>?</p>