Computer scienceProgramming languagesKotlinControl flowLambda expressions

Type-safe builders

DSL course builder

Report a typo

We have the following code to create a Course with a list of students:

data class Student(val name: String, val age: Int)

data class Course(val name: String, val students: MutableList<Student> = mutableListOf())

class CourseBuilder {
    var name: String = ""
    private val students = mutableListOf<Student>()

    fun name(value: String) {
        name = value
    }

    fun student(block: StudentBuilder.() -> Unit) {
        // ?
    }

    fun build(): Course {
        return Course(name, students)
    }
}

class StudentBuilder {
    var name: String = ""
    var age: Int = 0

    fun name(value: String) {
        name = value
    }

    fun age(value: Int) {
        age = value
    }

    fun build(): Student {
        return Student(name, age)
    }
}


fun buildCourse(block: CourseBuilder.() -> Unit): Course {
    // ?
}

Please complete the code using DSL to create a course with a list of students.

Sample Input 1:

Test John 30 Anne 20

Sample Output 1:

Course(name=Test, students=[Student(name=John, age=30), Student(name=Anne, age=20)])
Write a program in Kotlin
data class Student(val name: String, val age: Int)

data class Course(val name: String, val students: MutableList<Student> = mutableListOf())

class CourseBuilder {
var name: String = ""
private val students = mutableListOf<Student>()

fun name(value: String) {
name = value
}

fun student(block: StudentBuilder.() -> Unit) {
// Write your code here
}

fun build(): Course {
return Course(name, students)
}
}

class StudentBuilder {
var name: String = ""
var age: Int = 0

fun name(value: String) {
name = value
}

fun age(value: Int) {
age = value
}

fun build(): Student {
return Student(name, age)
}
___

Create a free account to access the full topic