https://kotlinlang.org logo
Title
c

Carrascado

08/01/2020, 3:43 PM
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

Dominaezzz

08/01/2020, 3:46 PM
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

Carrascado

08/01/2020, 3:48 PM
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

Dominaezzz

08/01/2020, 3:55 PM
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

Carrascado

08/01/2020, 3:58 PM
Umm according to the tests the implementation of the pic is correct 🤔
They are all green
d

Dominaezzz

08/01/2020, 4:00 PM
Ohhh I see.
Yh weird ctor.
c

Carrascado

08/01/2020, 4:05 PM
In case you needed that kind of overflow handling what would you do instead of making the constructor handle it?
d

Dominaezzz

08/01/2020, 4:05 PM
Time.fromHours(...) + Time.fromMinutes(...) ......
c

Carrascado

08/01/2020, 4:11 PM
Are those static methods? Sorry, I don't understand very well what do you mean
d

Dominaezzz

08/01/2020, 4:12 PM
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

Carrascado

08/01/2020, 4:39 PM
Thank you! More people think the same, that constructor is a bit ugly
m

Matteo Mirk

08/13/2020, 9:01 AM
If you don’t want to repeat the calculations as you originally asked, just create private methods and use them in the constructor