Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This shows that the builder pattern can be expressed with implicit function types.
- Loading branch information
Showing
3 changed files
with
55 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Table(Row(Cell(A1), Cell(B1)), Row(Cell(A2), Cell(B2))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
} | ||
} |