title: What is the point of accept() method in Visitor pattern?
body: <p>There is a lot of talk on decoupling the algorithms from the classes. But, one thing stays aside not explained.</p>
  <p>They use visitor like this</p>
  <pre><code>abstract class Expr {
    public &lt;T&gt; T accept(Visitor&lt;T&gt; visitor) { return visitor.visit(this); }
  }
  
  class ExprVisitor extends Visitor{
    public Integer visit(Num num) {
      return num.value;
    }
  
    public Integer visit(Sum sum) {
      return sum.getLeft().accept(this) + sum.getRight().accept(this);
    }
  
    public Integer visit(Prod prod) {
      return prod.getLeft().accept(this) * prod.getRight().accept(this);
    }
  </code></pre>
  <p>Instead of calling visit(element) directly, Visitor asks the element to call its visit method. It contradicts the declared idea of class unawareness about visitors.</p>
  <p>PS1 Please explain with your own words or point to exact explanation. Because two responses I got refer to something general and uncertain.</p>
  <p>PS2 My guess: Since <code>getLeft()</code> returns the basic <code>Expression</code>, calling <code>visit(getLeft())</code> would result in <code>visit(Expression)</code>, whereas <code>getLeft()</code> calling <code>visit(this)</code> will result in another, more appropriate, visit invocation. So, <code>accept()</code> performs the type conversion (aka casting).</p>
  <p>PS3 <a href="http://andymaleh.blogspot.com/2008/04/scalas-pattern-matching-visitor-pattern.html" rel="noreferrer">Scala's Pattern Matching = Visitor Pattern on Steroid</a> shows how much simpler the Visitor pattern is without the accept method. <a href="http://en.wikipedia.org/wiki/Visitor_pattern#External_links" rel="noreferrer">Wikipedia adds to this statement</a>: by linking a paper showing &quot;that <code>accept()</code> methods are unnecessary when reflection is available; introduces term 'Walkabout' for the technique.&quot;</p>