Skip to content

Commit e732c1a

Browse files
committed
Bonus test: builder pattern
This shows that the builder pattern can be expressed with implicit function types.
1 parent 144546d commit e732c1a

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

tests/run/builder.check

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Table(Row(Cell(A1), Cell(B1)), Row(Cell(A2), Cell(B2)))

tests/run/builder.scala

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import collection.mutable.ArrayBuffer
2+
3+
class Table {
4+
val rows = new ArrayBuffer[Row]
5+
def add(r: Row): Unit = rows += r
6+
override def toString = rows.mkString("Table(", ", ", ")")
7+
}
8+
9+
class Row {
10+
val cells = new ArrayBuffer[Cell]
11+
def add(c: Cell): Unit = cells += c
12+
override def toString = cells.mkString("Row(", ", ", ")")
13+
}
14+
15+
class Cell(elem: String) {
16+
override def toString = s"Cell($elem)"
17+
}
18+
19+
object Test {
20+
21+
def table(init: implicit Table => Unit) = {
22+
implicit val t = new Table
23+
init
24+
t
25+
}
26+
27+
def row(init: implicit Row => Unit)(implicit t: Table) = {
28+
implicit val r = new Row
29+
init
30+
t.add(r)
31+
}
32+
33+
def cell(str: String)(implicit r: Row) =
34+
r.add(new Cell(str))
35+
36+
val data =
37+
table {
38+
row {
39+
cell("A1")
40+
cell("B1")
41+
}
42+
row {
43+
cell("A2")
44+
cell("B2")
45+
}
46+
}
47+
48+
def main(args: Array[String]) = {
49+
println(data)
50+
}
51+
}

0 commit comments

Comments
 (0)