We want to create a type-safe builder to make an HTML table. The HTML Table has a list of rows. Here is the initial code:
class TableBuilder {
private val rows = mutableListOf<TableRowBuilder>()
fun row(block: TableRowBuilder.() -> Unit) {
val rowBuilder = TableRowBuilder()
rowBuilder.block()
rows.add(rowBuilder)
}
fun build(): String {
val tableContent = buildString {
append("<table>")
for (row in rows) {
// Write your code here
}
append("</table>")
}
return tableContent
}
}
class TableRowBuilder {
private val cells = mutableListOf<String>()
fun cell(value: String) {
cells.add(value)
}
fun build(): String {
val rowContent = buildString {
append("<tr>")
for (cell in cells) {
// Write your code here
}
append("</tr>")
}
return rowContent
}
}
fun table(block: TableBuilder.() -> Unit): String {
// Write your code here
}
Please complete the code to obtain the following result:
fun main() {
val htmlTable = table {
row {
cell("Name")
cell("Age")
}
row {
cell("John Doe")
cell("25")
}
row {
cell("Jane Smith")
cell("30")
}
}
println(htmlTable)
}
<table>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>John Doe</td>
<td>25</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>30</td>
</tr>
</table>