DTOs and nullable types


#1

Hello, I have some doubts on how to handle the following situation. Let’s say I have a dto (this is a simplified example just to frame the problem)

class ExampleDto {
   var arrayOfStuff: ArrayList<String> = ????
}

where:

  • I need to assign a default dummy value to arrayOfStuff. I don’t want it nullable. The initialization code may be complex and out of my hands, I still need to create the object beforehand, but after the inizialization phase is done that thing is never going to be null, so I don’t want the code after that to have to do null checks. I also don’t want multiple classes, one for the initialization and one for what happens afterward.
  • Using : List<String> = emptyList() is not going to cut it because I really want to deal with an ArrayList afterward
  • ArrayList type parameter is not covariant (unlike List) so I can’t use something analogous to what is in kotlin.collections to define my own object EmptyArrayList : ArrayList<Nothing> ... and relative emptyArrayList function

One option is just creating a new ArrayList() every time, but that looks a bit wasteful. Am I missing any other?


#2

Arright, googling some more I just discovered the existence of lateinit. That should solve the problem. Only one question though: not that it matters in my use-case, but I guess lateinit implies a null check on every property read?


#3

I know for a fact, that non-nullable function parameters are null-checked in every function invocation (to ensure it plays well when invoked from Java).

So I would assume it is not much different for lateinit properties.