Leonardo Borges
01/18/2022, 12:03 PMtoDomain()
function. But in this case, I don't know how to do it. Since I'm new to sealed class, maybe there is a solution which I haven't found...
The sealed class (domain) is something like:
sealed class TypeInstruction(val type: String) {
data class TypeOne(val isRequired: Boolean, val maxConcurrency: Short) : TypeInstruction(type = "typeOne")
data class TypeTwo(val isRequired: Boolean, val maxAttemps: Short): TypeInstruction(type = "typeTwo")
}
And the resource is:
sealed class TypeInstructionResource(val type: String) {
data class TypeOne(val isRequired: Boolean, val maxConcurrency: Short) : TypeInstruction(type = "typeOne")
data class TypeTwo(val isRequired: Boolean, val maxAttemps: Short): TypeInstruction(type = "typeTwo")
}
Then an extended function:
fun TypeInstructionResource.toDomain() = when(type) {
"typeOne" -> TypeInstruction.TypeOne(isRequired = isRequired, maxConcurrency = maxConcurrency)
"typeTwo" -> TypeInstruction.TypeTwo(isRequired = isRequired, maxAttemps = maxAttemps)
else -> /* */
}
But of course, the extended function does not recognize the "children" values, such as isRequired
. Any suggestions?Ties
01/18/2022, 12:16 PMis TypeOne
then it will automaticall cast it 🙂Ties
01/18/2022, 12:18 PMfun TypeInstructionResource.toDomain() = when(type) {
is TypeOne -> TypeInstruction.TypeOne(isRequired = isRequired, maxConcurrency = maxConcurrency)
is TypeTwo -> TypeInstruction.TypeTwo(isRequired = isRequired, maxAttemps = maxAttemps)
}
and also no else branch, since it is a sealed class this is not needed 🙂Leonardo Borges
01/18/2022, 12:19 PMTies
01/18/2022, 12:19 PMTies
01/18/2022, 12:22 PMsealed class TypeInstruction {
data class TypeOne(val isRequired: Boolean, val maxConcurrency: Short) : TypeInstruction()
data class TypeTwo(val isRequired: Boolean, val maxAttemps: Short): TypeInstruction()
}
sealed class TypeInstructionResource {
data class TypeOne(val isRequired: Boolean, val maxConcurrency: Short) : TypeInstructionResource()
data class TypeTwo(val isRequired: Boolean, val maxAttemps: Short): TypeInstructionResource()
}
fun TypeInstructionResource.toDomain() = when(this) {
is TypeInstructionResource.TypeOne -> TypeInstruction.TypeOne(isRequired = isRequired, maxConcurrency = maxConcurrency)
is TypeInstructionResource.TypeTwo -> TypeInstruction.TypeTwo(isRequired = isRequired, maxAttemps = maxAttemps)
}
Leonardo Borges
01/18/2022, 12:23 PMthis
solved it.Ties
01/18/2022, 12:23 PMLeonardo Borges
01/18/2022, 12:23 PMTies
01/18/2022, 12:24 PM