Computer scienceProgramming languagesKotlinControl flowLambda expressions

Type-safe builders

Person problem

Report a typo

We have the following code:

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

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

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

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

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

Please code buildPerson as a type-safe builder. It takes a lambda with a receiver (PersonBuilder.() -> Unit).

Sample Input 1:

John 30

Sample Output 1:

Person(name=John, age=30)
Write a program in Kotlin
data class Person(val name: String, val age: Int)

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

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

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

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

fun buildPerson(block: PersonBuilder.() -> Unit): Person {
// Write your code here
}
___

Create a free account to access the full topic