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?
First of all, if you want to work with abstract validatable objects, you need
Validatable
interface:You also need a class which represents a validated object:
Now you need
Validatable.valid()
function which helps to createValid
instances:Here is how you can make your
RequestModel
beValidatable
:And here is how you can use it:
You can also make
Valid
class inline. Since inline classes can't haveinit
blocks,init
logic is moved to the factory method. And since inline class primary constructor should bepublic
, the constructor is marked with@Experimental private annotation class ValidInternal
which prevents illegal constructor use: