Inconsistency in Java 8 method signatures

后端 未结 3 428
名媛妹妹
名媛妹妹 2021-02-08 09:46

Java 8 has given us new methods with really long signatures like this:

static > Collector toMap(
    Function&l         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-02-08 10:21

    Looking at the implementation of the Collectors#toMap in question, one can see that the operator is passed through to some other methods, but eventually only arrives as the remappingFunction in various forms of Map#merge(K key, V value, BiFunction remappingFunction).

    So using BiFunction instead of BinaryOperator would indeed work here, without causing any problem. But not only here: The BinaryOperator is only a specialization of BiFunction for the case that the operands and the result are all of the same type. So there are many places where one could allow passing in a BiFunction instead of a BinaryOperator (or, more obviously: One could always use a BiFunction instead...)


    So up to this point, there seems to be no technical reason why they chose to only support a BinaryOperator.

    There was already speculation about possible non-technical reasons. For example, limiting the complexity of the method signature. I'm not sure whether this applies here, but it could, indeed, be a trade-off between the complexity of the method and the intended application cases: The concept of a "binary operator" is easily comprehensible, for example, by drawing analogies to a simple addition or the union of two sets - or maps, in this case.

    A possible not-so-obvious technical reason could be that there should be the possibility to provide implementations of this method that internally would not be able to cope with the BiFunction. But considering that the BinaryOperator is only a specialization, it's hard to imagine what such an implementation should look like.

提交回复
热议问题