If I have a function that takes a `String` and par...
# getting-started
d
If I have a function that takes a
String
and parses it to return some
MyDataClass
, is it idiomatic in Kotlin to return
MyDataClass?
which is
null
if the input String doesn't match the pattern? Or should I use a
Result
or throw an exception or something? In this case returning
null
would happen "normally" and would not be exceptional in any way
r
This isn't a question of idiomatic so much as use case. Basically, is failure to parse an expected or exceptional situation, and what kind (if any) information do you expect to receive on parse failure?
If it's exceptional (meaning you expect it to succeed and can't/won't handle the situation where it fails), throw an exception. if it's expected, do you need to know why it failed or just that it failed? If you need to know why, return a result. If you don't care why, nullable works great.
d
Great, thanks. I think my particular use case is definitely the last category.
👍 1
e
A sealed class instead of an null maybe another option
r
@earroyoron Why? If all OP needs to know is that parsing failed, there's no need to create a type hierarchy to represent missing data when that is precisely what
null
is for.
e
You are right. It was "maybe" Also I am starting with kotlin so my opinion is too weak. I came from Java where we love null (and nullPointerException) 🤪
r
As do I 🙂 I've just noticed this weird trend in Kotlin developers to treat null as if it's somehow evil and should be avoided at all costs. @elizarov has a couple really good posts about it: https://medium.com/@elizarov/null-is-your-friend-not-a-mistake-b63ff1751dd5 https://medium.com/@elizarov/dealing-with-absence-of-value-307b80534903
🤗 1