Instance Creation Expressions

Constructor invocations

Instance creations are written using NEW(path|typ|"C"):

import treehugger.forest._, definitions._, treehuggerDSL._
object sym {
  val A = RootClass.newClass("A")
}
NEW(sym.A)                   // new A
NEW("C")                     // new C
NEW(REF("B") DOT "C")        // new B.C

Optionally, arguments may be passed into the constructor using NEW(path|typ|"C", arg, ...):

val tree = NEW("C", LIT(0), LIT(1))
// tree: Tree = Apply(
//   Select(New(TypeTree()), TermName("<init>")),
//   List(Literal(Constant(0)), Literal(Constant(1)))
// )

treeToString(tree)
// res3: String = "new C(0, 1)"

Anonymous classes

Anonymous classes are created by passing ANONDEF(parent|"C", ...) into NEW(...):

val tree2 = NEW(ANONDEF() := BLOCK(
  DEF("name") := LIT("Robert")
))
val tree3 = NEW(ANONDEF("C") := BLOCK(
  DEF("name") := LIT("Robert")
))
val tree4 = NEW(ANONDEF("C") withEarlyDefs(
  VAL("name") := LIT("Robert")
))

These examples print as:

treeToString(tree2)
// res4: String = """new {
//   def name = "Robert"
// }"""

treeToString(tree3)
// res5: String = """new C {
//   def name = "Robert"
// }"""

treeToString(tree4)
// res6: String = """new {
//   val name = "Robert"
// } with C"""