为了在scala中获得implicits
的支持,我尝试并且不太能够复制Martin Odersky的讲话中的表格示例(时间41:22):https://www.youtube.com/watch?v=YXDm3WHZT5g
这是我的尝试。它的工作原理除了我似乎无法摆脱暗示thisTable
和thisRow
:
object Prog {
class Table {
private var rows: Seq[Row] = Seq()
def add(row: Row) = rows = rows :+ row
override def toString(): String = {
s"Table(${rows.mkString(", ")})"
}
}
class Row {
private var columns: Seq[Column] = Seq()
def add(col: Column) = columns = columns :+ col
override def toString(): String = {
s"Row(${columns.map(_.content).mkString(", ")})"
}
}
case class Column(content: String)
def table(initTable: Table => Unit): Table = {
val t = new Table()
initTable(t)
t
}
def row(initRow: Row => Unit)(implicit table: Table): Row = {
val r = new Row()
initRow(r)
table.add(r)
r
}
def cell(content: String)(implicit row: Row) = {
row.add(new Column((content)))
}
def main(args: Array[String]): Unit = {
val t:Table =
table { implicit thisTable => // How can I get rid of this "implicit thisTable"?
row { implicit thisRow => // How can I get rid of this "implicit thisRow"?
cell("cellA1")
cell("cellB1")
}
row { implicit thisRow =>
cell("cellA2")
cell("cellB2")
}
}
println(t)
}
}
如何实现构建语法,如演讲中所示?
我试图在implicit
和table
函数的参数类型前面移动row
关键字,但是一旦我这样做,编译器就开始在我的几个地方咆哮(“错误的类型”,“缺少参数类型:表” ,“';'或换行符预期”,....)
谢谢