класс, у которого есть наследники LightWeightShip, MediumShip, HeavyShip. В настоящее время я проверяю тип объекта с использованием when + is, но есть довольно много повторяющегося кода.
private fun convertShipToShipData(
ships: List<Ship>,
outputShipData: MutableList<ShipDTO>
) {
ships.forEach { ship ->
val containersAsString = ship.getCurrentContainers().map { it.toString() }
when (ship) {
is LightWeightShip -> {
outputShipData.add(
ShipDTO(
id = ship.id,
fuel = ship.fuel,
portId = ship.currentPort.id,
totalWeightCapacity = ship.totalWeightCapacity,
maxNumberOfAllContainers = ship.maxNumberOfAllContainers,
maxNumberOfBasicContainers = ship.maxNumberOfBasicContainers,
maxNumberOfHeavyContainers = ship.maxNumberOfHeavyContainers,
maxNumberOfRefrigeratedContainers = ship.maxNumberOfRefrigeratedContainers,
maxNumberOfLiquidContainers = ship.maxNumberOfLiquidContainers,
fuelConsumptionPerKM = ship.fuelConsumptionPerKM,
containers = containersAsString
)
)
}
is MediumShip -> {
outputShipData.add(
ShipDTO(
id = ship.id,
fuel = ship.fuel,
portId = ship.currentPort.id,
totalWeightCapacity = ship.totalWeightCapacity,
maxNumberOfAllContainers = ship.maxNumberOfAllContainers,
maxNumberOfBasicContainers = ship.maxNumberOfBasicContainers,
maxNumberOfHeavyContainers = ship.maxNumberOfHeavyContainers,
maxNumberOfRefrigeratedContainers = ship.maxNumberOfRefrigeratedContainers,
maxNumberOfLiquidContainers = ship.maxNumberOfLiquidContainers,
fuelConsumptionPerKM = ship.fuelConsumptionPerKM,
containers = containersAsString
)
)
}
is HeavyShip -> {
outputShipData.add(
ShipDTO(
id = ship.id,
fuel = ship.fuel,
portId = ship.currentPort.id,
totalWeightCapacity = ship.totalWeightCapacity,
maxNumberOfAllContainers = ship.maxNumberOfAllContainers,
maxNumberOfBasicContainers = ship.maxNumberOfBasicContainers,
maxNumberOfHeavyContainers = ship.maxNumberOfHeavyContainers,
maxNumberOfRefrigeratedContainers = ship.maxNumberOfRefrigeratedContainers,
maxNumberOfLiquidContainers = ship.maxNumberOfLiquidContainers,
fuelConsumptionPerKM = ship.fuelConsumptionPerKM,
containers = containersAsString
)
)
}
}
}
}
а какой смысл проверять, если поля одинаковые?
Одинаковые, но классы наследники имплементируют от класса только функции, а не проперти, поэтому здесь нужен каст
ну пусть имплементируют проперти
есть, спасибо
Обсуждают сегодня