Gleb Garipov
02/22/2021, 9:55 AMsealed class WriteOperation {
data class Insert(...some props): WriteOperation()
data class Delete(...some props): WriteOperation()
data class Replace... and so on
}
// And then in mongo-related package I do:
fun WriteOperation.toMongoModel(): WriteModel = when (this) {
is WriteOperation.Insert -> InsertOneModel(...initialization)
is WriteOperation.Delete -> DeleteOneOperation(...initialization)
is WriteOperation.Replace -> ...
... and also around 12 other conditions
}
// Same thing happens with SQL:
fun WriteOperation.toSqlQuery(): SQLQuery = when (this) {
...long and painful list
}
Is there any way of replacing those long when expressions with some kind of inheritance, extension or composition without referencing Mongo or SQL implementation in sealed classes?Youssef Shoaib [MOD]
02/22/2021, 10:29 AMGleb Garipov
02/22/2021, 10:44 AMfun WriteOperation.toMongoModel() = TODO("I gonna throw")
fun WriteOperation.Insert.toMongoModel() = InsertOneModel(...)
fun doSomeCalc(op: WriteOperation) = op.toMongoModel()
doSomeCalc(WriteOperation.Insert(...))
Will always throw an exception, and it makes sense if you think of it.Cicero
02/22/2021, 10:46 AMGleb Garipov
02/22/2021, 10:53 AMGleb Garipov
02/22/2021, 11:47 AMWriteOperation
to target type, since actual type (Insert, Delete, etc.) is only known at runtime, and any kind of extension will always reference base class. I was also thinking about adding some generic mapping method to sealed class itself but it useless as well, because you'll need to know in what type such mapping should result at compile time... and you can not override it in your specific DB package anyway. So, good old when
expressions I guess 🙂