NLinker

Java: val vs explicit type

Jul 18th, 2017
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!

Why val over the explicit type

  1. Variable name is much more important and with val they could be found much more easily.
    Compare

    final UUID startingUuid = uuidsFrom.get(i);
    final Optional<CommonSong> theSongFrom = songsFrom.get(i);
    final Optional<CommonSong> theSongTo = songsTo.get(i);

    and

    val startingUuid = uuidsFrom.get(i);
    val theSongFrom = songsFrom.get(i);
    val theSongTo = songsTo.get(i);
  2. It is redundant for the simple cases like this

    final Borsht borsht = new Borsht();

    the type is obvious.

  3. Lazy programmers don't write final modifier, so val is concise shortcut for this too.

  4. The type can be easily viewed with Ctrl+Q

Although, for the complex cases I vote for writing the type explicitly, like

    Map<UUID, List<DeviceInfo>> mapDis = new HashMap<>(userIds.size());
    pairs.forEach(p -> {
           // we must not inline dis, since computeIfAbsent has side effect
           List<DeviceInfo> dis = mapDis
               .computeIfAbsent(p.getLeft(),
                   // just not to waste memory, we think user has usually 1 device
                   k -> new ArrayList<>(1));
            p.getRight().ifPresent(dis::add);
        }
    );
Add Comment
Please, Sign In to add comment