skip to Main Content

Is there a way I can use the magic of generics to write a function that returns an optional if the input is optional, otherwise both non-null?

For example, I have two functions that I want to combine into one.

static Timestamp dateToTimestamp(DateTime dateTime) {
  return Timestamp.fromDate(dateTime);
}
static Timestamp? dateToTimestampOptional(DateTime? dateTime) {
  return (dateTime == null) ? null : Timestamp.fromDate(dateTime);
}

2

Answers


  1. Make the type as generic

      Timestamp? dateToTimestamp<T extends DateTime?>(T dateTime) {
         return (dateTime == null) ? null : Timestamp.fromDate(dateTime); 
      }
    
    Login or Signup to reply.
  2. Here’s how you can combine the two functions into one using generics:

    T? dateToTimestamp<T extends DateTime?>(T? dateTime) {
      return dateTime?.toTimestamp();
    }
    

    Usage:

    // With DateTime argument (non-null)
    Timestamp timestamp = dateToTimestamp(DateTime.now());
    
    // With DateTime? argument (optional)
    DateTime? maybeDateTime;
    Timestamp? maybeTimestamp = dateToTimestamp(maybeDateTime);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search