From cf9741297a8bb91a26841d970be38436565a62c8 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Sat, 18 Feb 2017 12:55:23 +0100 Subject: Bonus test: builder pattern This shows that the builder pattern can be expressed with implicit function types. --- tests/run/builder.check | 1 + tests/run/builder.scala | 51 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 tests/run/builder.check create mode 100644 tests/run/builder.scala (limited to 'tests/run') diff --git a/tests/run/builder.check b/tests/run/builder.check new file mode 100644 index 000000000..48f7d9253 --- /dev/null +++ b/tests/run/builder.check @@ -0,0 +1 @@ +Table(Row(Cell(A1), Cell(B1)), Row(Cell(A2), Cell(B2))) diff --git a/tests/run/builder.scala b/tests/run/builder.scala new file mode 100644 index 000000000..532a95071 --- /dev/null +++ b/tests/run/builder.scala @@ -0,0 +1,51 @@ +import collection.mutable.ArrayBuffer + +class Table { + val rows = new ArrayBuffer[Row] + def add(r: Row): Unit = rows += r + override def toString = rows.mkString("Table(", ", ", ")") +} + +class Row { + val cells = new ArrayBuffer[Cell] + def add(c: Cell): Unit = cells += c + override def toString = cells.mkString("Row(", ", ", ")") +} + +class Cell(elem: String) { + override def toString = s"Cell($elem)" +} + +object Test { + + def table(init: implicit Table => Unit) = { + implicit val t = new Table + init + t + } + + def row(init: implicit Row => Unit)(implicit t: Table) = { + implicit val r = new Row + init + t.add(r) + } + + def cell(str: String)(implicit r: Row) = + r.add(new Cell(str)) + + val data = + table { + row { + cell("A1") + cell("B1") + } + row { + cell("A2") + cell("B2") + } + } + + def main(args: Array[String]) = { + println(data) + } +} -- cgit v1.2.3