Tag: 逆变

在Stream.reduce()这样的API中选择不变性有什么好理由?

回顾Java 8 Stream API设计,我对Stream.reduce()参数的generics不变性感到惊讶: U reduce(U identity, BiFunction accumulator, BinaryOperator combiner) 相同API的看似更通用的版本可能对U单个引用应用了协方差/逆变,例如: U reduce(U identity, BiFunction accumulator, BiFunction combiner) 这将允许以下目前无法实现的目标: // Assuming we want to reuse these tools all over the place: BiFunction numberAdder = (t, u) -> t.doubleValue() + u.doubleValue(); // This currently doesn’t work, but would work with the suggestion Stream stream = […]

为什么Java中的逆变参数类型不允许覆盖?

覆盖超类的方法时,Java允许返回类型是协变的。 为什么在重写方法时不允许使用逆变参数类型?