Computer scienceProgramming languagesKotlinControl flowLambda expressions

Type-safe builders

HTML table

Report a typo

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>

Sample Input 1:

Name Age John 25 Jane 30

Sample Output 1:

<table><tr><td>Name</td><td>Age</td></tr><tr><td>John</td><td>25</td></tr><tr><td>Jane</td><td>30</td></tr></table>
Write a program in Kotlin
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>")
}
___

Create a free account to access the full topic