https://kotlinlang.org logo
#android
Title
# android
m

menegatti

06/08/2017, 8:02 AM
why not a factory method to return null when necessary instead?
j

jasonlow

06/08/2017, 8:08 AM
menegatti: Can you elaborate on what you mean by that?
m

menegatti

06/08/2017, 8:09 AM
well, have a companion object with a method that takes the json and returns null in case it's not valid
I don't think data classes have a really good way of achieving what you're trying to do by themselves
j

jasonlow

06/08/2017, 8:11 AM
To extend on your point for a companion object, why not a function instead that massages the json and return null if not valid?
If not a data class, then what?
m

menegatti

06/08/2017, 8:12 AM
I mean, you would still use a data class
but a method will work on the instance itself and validating the json should be a step before, don't you agree?
meaning... you verify whether or not it is a valid json and then decide on whether you should create an instance of the data class or not
so it seems like a case where I would use a static (companion object) factory method that takes a json and returns your class in case the json is valid, null otherwise
j

jasonlow

06/08/2017, 8:16 AM
I see where you’re getting at now. Interesting, never thought of that. Will give it a shot.
Have you personally never encountered such cases before though?
OR, alternatively we could make the constructors throw an exception, no?
m

menegatti

06/08/2017, 8:21 AM
yes, definitely
j

jasonlow

06/08/2017, 8:21 AM
Noted, thanks Edson!
m

menegatti

06/08/2017, 8:21 AM
also you could let the json do its magic
and after parsing you just filter out the instances that don't pass a certain validation, does that make sense?
j

jasonlow

06/08/2017, 8:22 AM
Haha, I thought of that too actually
m

menegatti

06/08/2017, 8:23 AM
if you wanna go very clean about it, have an interface like
Validator
with a method
validate
or something, and filter out by the return of validate, but then it's a matter of taste
k

kirillrakhman

06/08/2017, 8:47 AM
constructors throwing exceptions are bad style. I support the suggestion for a factory method.
Kotlin's nullability language features lend themselves very well for early returns:
Copy code
fun create(json: JosnObject): MyClass? {
    val id = json.opt("id") ?: return null
    ...
    return MyClass(id, foo, bar, ...)
}