I'm thinking about rewriting small web server project that I have from TypeScript to Kotlin. The problem that I have is server accepts a JSON with unions and intersections. For the purpose of this example:
- I want incoming JSON to have a string field with either the name
oneor nametwo, but not both or none of them, e.g.{"one": "some text"}or{"two": "some other text"} - I want format of incoming request be dependent on one of its fields, e.g.:
{
"someFlag": false, // or can be missing
"ids": {
"user": 123 // mandatory field for this structure
}
}
or if someFlag exists and true, it makes couple more extra id fields mandatory
{
"someFlag": true
"ids": {
"user": 123,
"company": 456, // mandatory because someFlag is true
"device": 789 // mandatory because someFlag is true
}
}
Unions and intersections within same type is quite trivial in TS, but I have no idea how to achieve same thing in Kotlin and then utilize validated request in a typesafe manner. I'm pretty sure I can try to figure out some "dirty" approach with bunch of optional fields and manual checks for field existence on multiple program levels, but if there's a way to make it typesafe, I'd rather take it.
So the question is, can I make this validation typesafe?