Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8336847

Use pattern match switch in NumberFormat classes

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 24
    • None
    • core-libs
    • b08
    • generic
    • generic

      Eg in NumberFormat.format(Object, StringBuffer, FieldPosition)

      ```
              if (number instanceof Long || number instanceof Integer ||
                  number instanceof Short || number instanceof Byte ||
                  number instanceof AtomicInteger || number instanceof AtomicLong ||
                  (number instanceof BigInteger &&
                   ((BigInteger)number).bitLength() < 64)) {
                  return format(((Number)number).longValue(), toAppendTo, pos);
              } else if (number instanceof Number) {
                  return format(((Number)number).doubleValue(), toAppendTo, pos);
              } else {
                  throw new IllegalArgumentException("Cannot format given Object as a Number");
              }
      ```
      can be simplified to:
      ```
              return switch (number) {
                  case Long l -> format(l.longValue(), toAppendTo, pos);
                  case Integer i -> format(i.longValue(), toAppendTo, pos);
                  case Short s -> format(s.longValue(), toAppendTo, pos);
                  case Byte b -> format(b.longValue(), toAppendTo, pos);
                  case AtomicInteger ai -> format(ai.longValue(), toAppendTo, pos);
                  case AtomicLong al -> format(al.longValue(), toAppendTo, pos);
                  case BigInteger bi when bi.bitLength() < 64 -> format(bi.longValue(), toAppendTo, pos);
                  case Number n -> format(n.doubleValue(), toAppendTo, pos);
                  default -> throw new IllegalArgumentException("Cannot format given Object as a Number");
              };
      ```

            jlu Justin Lu
            naoto Naoto Sato
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: