I have programmed a mini-class for practicing Kotl...
# getting-started
c
I have programmed a mini-class for practicing Kotlin. I'm getting really confused with how I could properly initialize these class properties without repeating the operations. I'm trying that whenever you initialize the
Time
class with more than 59 minutes, or more than 59 seconds, it automatically gets adjusted
d
That's a weird ctor IMO. I think you should just assert that the params are within range, instead of handling the overflow.
Then maybe have a
Time.fromMinutes(...)
.
You can reference the properties in
init
using the
this
qualifier.
c
Honestly it's just for the sake of practice, although I see it very convenient that some kind of "Value Object" like this could handle the overflow by itself
Thank you for the suggestion, I don't know If it's more readable than before 😂
But it's true that it feels more natural to me this way
I guess the intrinsic complexity of handling that overflow can't be lower than that
In case that I just asserted the values are within the desired range, would you use some built-in exception in Kotlin? Or would you create one? @Dominaezzz
d
Actually, I think you're missing an edge case
val totalMinutes = minutes + (second - this.seconds) / 60
right?
Use a bult in exception I think. There should be one.
c
Umm according to the tests the implementation of the pic is correct 🤔
They are all green
d
Ohhh I see.
Yh weird ctor.
c
In case you needed that kind of overflow handling what would you do instead of making the constructor handle it?
d
Time.fromHours(...) + Time.fromMinutes(...) ......
c
Are those static methods? Sorry, I don't understand very well what do you mean
d
They should exists in the companion object of the
Time
class
Have methods to convert single units to a time object. Then a
plus
operator to handle overflows and such.
c
Thank you! More people think the same, that constructor is a bit ugly
m
If you don’t want to repeat the calculations as you originally asked, just create private methods and use them in the constructor