maybe this isn’t really the right approach within ...
# random
s
maybe this isn’t really the right approach within Kotlin, but is there any provision for validating data class constructor arguments?
g
In general: No, it's impossible to do properly. You can have private constructor and create an instance of your data class using factory function (with validation), but you cannot do that for
copy
method, so if you need validation, use common
class
instead of
data class
s
ahh, okay, I’ll keep this in mind 👍
g
But of course you can validate argument in init block and throw an exception after constructor invocation, but it's not what usually you want
Dependends on your case, what you want to do in case of failed check
s
in this particular case, I more or less just want to throw an exception - my use case involves intercepting the exception up the stack and translating it to an HTTP 400 with the validation error as the message body
contingent upon the type of exception, that is - not every exception should be translated to a 400, after all
g
Why not just return some result class, that can contain result or error?
s
my thinking was that it might be more DRY to just rely on an interceptor that’s automatically applied to my endpoints, but honestly I’m not married to the idea
I have been wrong before, and perhaps I am again 😅