Computer scienceProgramming languagesKotlinObject-oriented programmingObject-oriented programming features

Building your own delegate

Property as a delegate

Report a typo

You have a class Car with a property speed that is backed by a private field _speed. speed has a custom setter, which ensures that the speed of the car cannot be negative and prints a message to the console indicating the new speed of the car. For example if the new speed is 1010, the message will be: Speed set to 10.

Your task is to create another property named acceleration in the Car class, which delegates to the speed property. This means that when we get or set the value of the acceleration property, it will actually get or set the value of the speed property.

Additionally, inside the provided RaceCar class, create the boost property, which should delegate to the speed property of a Car instance.

Sample Input 1:

10
20

Sample Output 1:

Speed set to 10
Car acceleration: 10

Speed set to 20
Race car boost: 20
Car acceleration: 20
Write a program in Kotlin
class Car {
private var _speed = 0
var speed: Int
get() = _speed
set(value) {
if (value >= 0) {
_speed = value
println("Speed set to $value")
} else {
println("Speed cannot be negative")
}
}

// Declare the `acceleration` property and delegate it to `speed`

}

class RaceCar(private val car: Car) {

// Declare `boost` property that delegates to the property `speed` of the `car` instance

}
___

Create a free account to access the full topic