iex
02/21/2020, 5:27 PMdata class Flow(
val ids: List<MyId>,
val steps: MySteps
) {
constructor(ids: List<MyId>) : this(
ids,
MySteps(ids.toSteps(), ids.toSteps().first())
)
}
data class MySteps(val steps: List<MyStep>, val currentStep: MyStep)
How can I throw an error in the convenience constructor if ids
is not empty (such that it crashes before ds.toSteps().first()
?wbertan
02/21/2020, 5:33 PMconstructor(ids: List<MyId>) : this(
ids.ifEmpty { error("Not possible") },
MySteps(ids.toSteps(), ids.toSteps().first())
)
iex
02/21/2020, 5:37 PMstreetsofboston
02/21/2020, 5:38 PMoperator fun invoke(...): Flow { ... }
to the `Flow`'s companion object.wbertan
02/21/2020, 5:42 PMcompanion object {
operator fun invoke(ids: List<MyId>): Flow {
if(ids.isEmpty()) {
error("Not possible!")
}
return Flow(
ids,
MySteps(ids.toSteps(), ids.toSteps().first())
)
}
}
iex
02/21/2020, 5:49 PMstreetsofboston
02/21/2020, 5:53 PMdata class Flow private constructor(
val ids: List<MyId>,
val steps: MySteps
) {
companion object {
operator fun invoke(ids: List<MyId>) : Flow {
if (ids.isEmpty()) error("....)"
return Flow(ids, MySteps(ids.topSteps(), ids.toSteps().first())
}
}
}
Mike
02/21/2020, 6:00 PMstreetsofboston
02/21/2020, 6:05 PMFlow
or throwing an exception, but maybe something more like a Either<Error, Flow>
. A factory method can be changed to make that happen, a constructor can only return a Flow, never something elseiex
02/21/2020, 6:13 PMKroppeb
02/21/2020, 6:20 PMFlow?
Mike
02/21/2020, 6:30 PMEither
more and more as I like the separation of business errors from truly exceptional occurrences.