Search code examples
dartnulldart-null-safety

Create nullable object based on nullable value


i have to create a domain class object which has a nullable attribute. This Creating is in an extansion of a primitive class.

For example: Domainclass

Meeting({required String id, required Datetime date, Example? example})

behind Example is an class like so: Example(String value)

MeetingPrimitive.dart:

extension MeetingPrimitiveX on Meeting {

Meeting toDomain() {
  return Meeting(
    id: id,
    date: date,
    example: example == null ? null : Example(example)
}

}

My question is, how can i simplify this:

example == null ? null : Example(example)
'''


thanks in advance

Solution

  • You generally can't. You can change it in various ways, but nothing is more direct than what you have here.

    One variant would be:

    extension DoWith<T> on T {
      R doWith<R>(R Function(T) action) => action(this);
    }
    

    With that, you can write:

     example?.doWith(Example.new)
    

    to conditionally call the Example.new constructor (tear-off of the unnamed constructor) if example is non-null.

    Slightly shorter, requires a helper function, and ... isn't actually more readable IMO.