0

For my API I'm parsing an object and creating my object with the lombok builder. One of the variables is an "arrivalTime" of type LocalDateTime that, of course, could be null.

I used to have it like this:

visits.add(visit.builder()
      .arrivalTime(legacyVisit.getArrivalTime() == null ? null :
          LocalDateTime.parse(legacyVisit.getArrivalTime(), ISO_OFFSET_DATE_TIME))

But I'm looking into a nicer way of doing this, maybe using a vavr option? But I'm running into problems. I understand that I put into "map" the logic if it's not null and into "get" the logic if it's null. But I can't do get(null). If arrivalTime is null, I want to keep it as null.

visits.add(visit.builder()
      .arrivalTime(Option.of(legacyVisit.getArrivalTime())
          .map(p -> LocalDateTime.parse(p, ISO_OFFSET_DATE_TIME)))

I also tried converting my arrivalTime variable in my object to an Option but I just send the object as a response in my API and it turns it into something like this:

    "arrivalTime": {
        "empty": true,
        "lazy": false,
        "singleValued": true,
        "async": false,
        "defined": false,
        "orNull": null
    },

which is very ugly. Any ideas?

Naman
  • 27,789
  • 26
  • 218
  • 353
coconut
  • 1,074
  • 4
  • 12
  • 30
  • 2
    To answer the specific question "Keep null if empty", it's as simple as `.getOrElseNull()`. So you would have `Option.of(legacyVisit.getArrivalTime()).map(p -> LocalDateTime.parse(p, ISO_OFFSET_DATE_TIME)).getOrElseNull()`. But generally speaking, declaring your field of type `Option` in your API should be enough when you import `vavr-jackson`. That's what we do at my company. – Sir4ur0n Feb 28 '19 at 22:34

1 Answers1

2

It looks like having arrivalTime being an Option would be the most expressive and powerful. You can easily map the values as you mentioned.

But as mentioned, the serialization might need some work. There are some Vavr modules which do exactly that:

  • vavr-jackson which you could use when you're using jackson as JSON serializer library
  • vavr-gson which you could use when you're using GSON as JSON serializer library