CAR Class – The Interview Solution in Kotlin (1/2)
When I started searching for a new and possible better contract, I met with several job interviews and according to this – had some tasks to do. I decided to write every once in a while a post with a solution of typical tasks. For now, in this shot article series, we look into a Car Class task and we will try to find a good solution for it in Kotlin.
As first, read the below description of this task and in the second part of this article, you will be able to find my solution of it, so let’s roll.
Car Class
Write the solution and all codes as the car.kts file.
Write a Car class that will represent a real car. On a new instance creation, there will be able to pass four parameters as initial: brand (the brand name of a new car), engine_type (Diesel/Gasoline), tank_capacity (the maximum fuel capacity in liters) and tanked_fuel (initial fill in liters). On a successful creation, the following message must be written in the console window:
New car of brand <brand>, with tank full in XXX%.
Where <brand> should be replaced with the brand name, while XXX should be the percentage value of the car tank fill rounded to one decimal place. Objects of the Car class should be equipped with the following key methods:
- fill_tank with passing an argument fill_full set to true, will fill the car tank to the maximum its capacity. The method should return the number of filled liters of fuel.
- fill_tank with passing an argument liters, will fill the car tank with a specific amount of liters. In case if the maximum tank capacity exceeded, a program should throw an exception. The method should return the number of filled liters of fuel.
- fill_tank that in case of fill the Diesel car tank, will throw an EnvironmentalError exception with the following message: ON fuel not available, because of environmental restrictions. Change engine as soon, as possible.
- empty_tank with passing an argument limit, will drain the car tank to a specific limit, where the limit should be a decimal value of range <0;1> and represents the percentage fill of the car tank. For example, there is a car with 100l tank capacity filled to full. The empty_tank method call with limit set to 0.4 will dry the car tank with 60 liters. The method should return the number od dryed liters of fuel.
All method should be protected for passing unnecessary or illegal data. For example, there should not be a possibility to fill the car tank with 100 liters if the maximum capacity is 50 liters so on and so forfth.
Personally I think this task is very good for object oriented class based programming. If you don’t know how to solve it or just want to see my solution, be welcome to visit the second part.