title: How does AST Transformation object works?
body: <p>Can someone help me grasp the transformation object that allows ASTs modification in scala?</p>
  
  <p>There are many examples around the web but I'm having a hard time understanding how the recursion is happening.</p>
  
  <p>E.g. If I have this AST:</p>
  
  <pre><code>def foo = {
   true
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>def foo = true
  </code></pre>
  
  <p>And want to transform it to </p>
  
  <pre><code>def foo = {
   println("foo")
   true
  }
  </code></pre>
  
  <p>How does the transform function should look like. At this point I have something like this:</p>
  
  <pre><code>override def transform(tree: Tree) = tree match {
   case defdef @ DefDef(_,_,_,_,_,rhs) =&gt; rhs match{
     case b: Block =&gt; treeCopy.Block(b, createPrintln :: b.stats, b.expr)           
     case _ =&gt; //Manage functions without block
   }
   case t =&gt; super.transform(t)
  }
  
  private def createPrintln = Apply(Select(Ident("System.out"), newTermName("println")), List(Literal(Constant("foo"))))
  </code></pre>
  
  <p>But does not work, being honest I'm just applying what I see in examples but can't figure out how the tree is being constructed. An explanation "for dummies" would be appreciated.</p>
  
  <p>[Edit]</p>
  
  <p>Senia example is nice, but I'm still stuck when having a little more complex tree like:</p>
  
  <pre><code>imports bla.bla
  class MyObject{
  
    val x = 0
    def foo = true
    def foo2 = { 1 }
  }
  object MyObject
  </code></pre>
  
  <p>Expected result:</p>
  
  <pre><code>import bla.bla
  class MyObject{
  
    val x = 0
    def foo = { println("foo"); true }
    def foo2 = { println("foo"); 1 }
  }
  object MyObject
  </code></pre>