I'm a beginner with Kotlin and in this example given to me. it is quite confusing. Here is the code I have done for this:
import kotlin.math.sqrt
class Rectangle(val length: Double, val width: Double){
fun main(){
print("Length: ")
val length = input()
print("Width: ")
val width = input()
val rect = Rectangle(length,width)
rect.recDetails()
print("\nNew area: ")
var area = input()
rect.area = area
rect.recDetails()
}
private fun input() = readLine()!!.toDouble()
CodePudding user response:
Now that user can input new area and we need to recalculate the length and width, the first step would be to make them var.
After that, the only thing required now is calculating the new length and width when a new area is set. With some basic maths, you can figure out that:
Given area A, original length L and original width W:
newLength = sqrt(L*A/W) and newWidth = sqrt(W*A/L) // keeping the L/W ratio fixed
Just use these in the area setter
set(value: Double) {
field = value
val newLength = sqrt(value * length / width)
val newWidth = sqrt(value * width / length)
length = newLength
width = newWidth
}
Although I don't like modifying getters/setters for such calculations, its better to create a proper function for updating area. But since you specifically asked for the getter/setter approach, here it is.
