https://kotlinlang.org logo
Title
s

spicyspiders

09/19/2019, 2:27 AM
In a DTO data class containing
people: List<Person>?
is it safer to do
people: List<Person?>?
instead? i.e. people field can be null and also list containing null or empty?
a

Amirul Zin

09/19/2019, 2:38 AM
Maybe you want to consider how the DTO is actually created. 1. Can that property (and the actual list elements) ever be null? 2. Why not use a separate DTO with a common interface instead? 3. Does the actual consumer only needs an empty list or it also needs to check the nullability as a logic switch? Null is a valid state, but in Java land, it is over abused. My experience so far in Kotlin land, you want to use null precisely when it is really necessary. e.g. JSON input, DB input, IO inputs.
s

spicyspiders

09/19/2019, 3:08 AM
Good points to think about. Thanks. I'd say in this case we are interfacing with external systems we have no control over, so I they could send empty field or an empty list. 😄 So I'd go with
people: List<Person?>?
-- but am I correct in my assumption that this is the way to let kotlin know the whole field can be null or list of null is also valid?
a

Amirul Zin

09/19/2019, 5:33 AM
If so then yes. In fact, that is the most safest way to do it if you literally have no control or information about what being set. Then again, I had yet to see an API sending a homogenous list of non-null elements interspersed with null elements. 🤔
t

tddmonkey

09/19/2019, 7:34 AM
The API you’re interfacing with might allow it. but I could immediately switch it around it
List<Person>
so the rest of my domain doesn’t have to worry about it. It’s a one liner to convert
List<Person?>?
to
List<Person>
and saves null-safe dereferencing everywhere you need to use it
m

Matteo Mirk

09/19/2019, 8:27 AM
I agree, even if null usage can be necessary to interface with external sources, I would avoid a null list in favor of an empty one, and filter out null elements at the boundary
s

spicyspiders

09/20/2019, 1:05 AM
Good points @tddmonkey and @Matteo Mirk. Kotlin is making me overthink things sometimes. It's a bit of a blessing and a curse, as a beginner at least. 😄
👍 1