简体   繁体   中英

Is ? super/extends byte[] makes sense?

I just wrote following method.

static <R> R encodeBase16(final Supplier<? extends byte[]> supplier,
                          final Function<? super byte[], ? extends R> function) {
    requireNonNull(supplier, "supplier is null");
    requireNonNull(function, "function is null");
    return function.apply(encodeBase16(supplier.get()));
}

While the compiler seems have no problems with it.

Are those ? extends byte[] ? extends byte[] and ? super byte[] ? super byte[] parts makes sense? Or can I just use byte[] ?

static <R> R encodeBase16(final Supplier<byte[]> supplier,
                          final Function<byte[], ? extends R> function) {
    requireNonNull(supplier, "supplier is null");
    requireNonNull(function, "function is null");
    return function.apply(encodeBase16(supplier.get()));
}

This is fine. You can put any reference type after extends / super in a wildcard bound. See the production rule here :

TypeArguments:
  < TypeArgumentList >
TypeArgumentList:
  TypeArgument {, TypeArgument}
TypeArgument:
  ReferenceType 
  Wildcard
Wildcard:
  {Annotation} ? [WildcardBounds]
WildcardBounds:
  extends ReferenceType 
  super ReferenceType

As you know, using wildcards allows the possibility of subtypes of byte[] to be used as the type argument for an extends byte[] wildcard, and supertypes of byte[] to be used as the type argument for an super byte[] wildcard. As far as I know, there are no subtypes of byte[] and the only super types of byte[] are:

  • Object
  • Serializable
  • Cloneable

according to this . So for example you could pass a Function<Object, R> to that method:

Function<Object, String> function = x -> null;
encodeBase16(() -> null, function);

Is this useful ? I wouldn't say so, but you are allowed to do non-useful things.

Related question about "redundant" use of wildcards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM