强制类型而不创建临时变量

Coerce type without creating temporary variable

我有以下功能:

  <K, P, Q> Map<K, List<Q>> convert(Map<K, ? extends List<? extends P>> input) {
    return HashMap.empty();
  }

我是这样调用的:

Map<Integer, List<? extends String>> stringMap = HashMap.empty();
Map<Integer, List<? extends Double>> doubleMap = HashMap.empty();
Map<Integer, List<Boolean>> stringMapConverted = convert(stringMap);
Map<Integer, List<Boolean>> merged = stringMapConverted.merge(convert(doubleMap));

但是,我想执行此操作而不必先创建临时变量。
像这样:

Map<Integer, List<? extends String>> stringMap = HashMap.empty();
Map<Integer, List<? extends Double>> doubleMap = HashMap.empty();
Map<Integer, List<Boolean>> merged = convert(stringMap).merge(convert(doubleMap));

但是,我在这里遇到编译错误:

'merge(io.vavr.collection.Map<? extends java.lang.Integer,? extends io.vavr.collection.List<java.lang.Object>>)' in 'io.vavr.collection.Map' cannot be applied to '(io.vavr.collection.Map<java.lang.Integer,io.vavr.collection.List<? extends java.lang.Double>>)'

Required type: Map<? extends Integer,? extends List<Object>>
Provided: Map<Integer,List<? extends Double>>

我也试过显式转换:

Map<Integer, List<Boolean>> merged2 = ((Map<Integer,List<Boolean>>)convert(stringMap)).merge(doubleMap);

但它抛出一个编译错误:

Inconvertible types; cannot cast 'io.vavr.collection.Map<java.lang.Integer,io.vavr.collection.List<java.lang.Object>>' to 'io.vavr.collection.Map<java.lang.Integer,io.vavr.collection.List<java.lang.Boolean>>'

Map.merge()签名如下:

Map<K, V> merge(Map<? extends K, ? extends V> that);

地图和列表 类 来自 vavr

调用convert时使用type witness, or so called TypeArguments mentioned in 15.12 in SE11 JLS指定参数类型。

MethodInvocation:
  MethodName ( [ArgumentList] )
  TypeName . [TypeArguments] Identifier ( [ArgumentList] )
  ExpressionName . [TypeArguments] Identifier ( [ArgumentList] )
  Primary . [TypeArguments] Identifier ( [ArgumentList] )
  super . [TypeArguments] Identifier ( [ArgumentList] )
  TypeName . super . [TypeArguments] Identifier ( [ArgumentList] )
ArgumentList: Expression {, Expression}

注意在使用TypeArguments时不能省略实例名->(this).

Map<Integer, List<Boolean>> merged = this.<Integer, String, Boolean>convert(stringMap).merge(convert(doubleMap));