Home > Back-end >  "map.getOrDefault" equivalent in Dart
"map.getOrDefault" equivalent in Dart

Time:02-15

I'm working on a friend suggestion algorithm for a flutter social media application. I'm still an amateur when it comes to Dart so I'm stuck on the following line of code:

    if (mutual.id != user.id && !user.friends.contains(mutual)) {
      map.putIfAbsent(mutual, map.getOrDefault(mutual, 0)   1);
    }

map.getOrDefault is underlined (I know the method doesn't exist in Dart). Do you know what the equivalent is in Dart? (PS, I'm just translating Java code into Dart.

Any help is appreciated!

CodePudding user response:

You could do it like this:

map.putIfAbsent(mutual, (map.containsKey(mutual) ? map[mutual] : 0)   1)

Maybe take a look at this for more info: https://dart.dev/guides/language/language-tour#conditional-expressions

CodePudding user response:

Your code doesn't make sense. map.putIfAbsent will do work only if the key doesn't exist, so the hypothetical map.getOrDefault call with the same key would always return the default value anyway. That is, your logic would be the equivalent of map.putIfAbsent(mutual, () => 1), where nothing happens if the key already exists.

Map.putifAbsent takes a callback as its argument to avoid evaluating it unless it's actually necessary. I personally prefer using ??= when the Map values are non-nullable.

I presume that you actually want to increment the existing value, if one exists. If so, I'd replace the map.putIfAbsent(...) call with:

map[mutual] = (map[mutual] ?? 0)   1;

Also see: Does Dart have something like defaultdict in Python?

  • Related