I have a class with some nullable properties
data class RequestModel(
val description: String?
)
and a validation function
fun validate(model: RequestModel): RequestModel{
if(model.description == null) throw IllegalArgumentException("description must be non null")
return model
}
After this validation step, I need a way to indicate non-nullability of description property.
One solution is to create a new data class which has non null propertis data class RequestModel(val description: String).
But I'm looking for a generic way to avoid creating new classes per use case.
Ideal generic solution:
fun validate(model: RequestModel): NoNullableField<RequestModel>
How can I remove nullability from properties of a class with nullable properties in a generic way? Is it usefull to use some kind of kotlin compiler contract?
You can use Kotlin reflection to get all properties and check if they are not null:
Use case:
Also, you can extract
validated[RequestModel::description]to an extension property ofNoNullableProperties<RequestModel>:Where
ValidRequestModelis:Use case: