andyg
06/28/2020, 8:18 PMdata class counters(var small: Int, var big: Double)
fun Int.add3() : Int = this + 3 // accepts Int, returns Int
fun Double.times2pt5() : Double = this * 2.5
fun main() {
val mycounters : counters = counters(4, 201.0)
mycounters.small.apply{ this.add3() }
mycounters.apply { this.big.times2pt5() }
println(mycounters) // prints 4, 201.0 -- same as original
val uglyCounters : counters = counters(6, 401.0)
uglyCounters.apply {
this.small = this.small.add3()
this.big = this.big.times2pt5()
}
println(uglyCounters) // works, prints 9, 1002.5, but is ugly
}
Jonathan Mew
06/29/2020, 9:17 AMdata class Counters(var small: Int, var big: Double) {
fun add3() {
small += 3
}
fun times2pt5() {
big *= 2.5
}
Jonathan Mew
06/29/2020, 9:18 AMandyg
07/01/2020, 7:06 PMcounters
is not a good idea, they would have to be replicated for every superclass.andyg
07/01/2020, 7:12 PMsmall
and big
are semi-complex objects of their own, not single values. The use case is, I want to manipulate the inner objects using their own methods, and have the outer object be able to reference the inner object post-manipulation.Jonathan Mew
07/02/2020, 7:38 AMcounters
class? Will that cause repeated code or something? A few ways to achieve what you want but it's hard to know what would be most appropriate from your example...andyg
07/02/2020, 4:49 PMcar.engine.start()
, and if you later polled garage.vehicles.started.length
it should return 1 (this is what doesn't happen in to mycounters that I'm trying to fix). Not garage.engine.start(car)
(because it doesn't make logical sense) and not garage.apply {car = car.engine.start()}
(i.e. reassignment).Jonathan Mew
07/03/2020, 7:44 AMval garage = Garage()
val car = Car()
val truck = Truck()
garage.add(car)
garage.add(truck)
car.engine.start()
fun Garage.runningVehicles() = getVehicles().filter { it.isStarted() }.size
Jonathan Mew
07/03/2020, 7:47 AMandyg
07/03/2020, 7:19 PMCar -> Car
. Because we didn't re-assign, i.e. garage.car = car.engine.start()
the garage still contains the old "unstarted" car, thus runningVehicles will return zero.andyg
07/03/2020, 7:20 PMJonathan Mew
07/06/2020, 7:50 AM