Why it works: BigDecimal Sum with Reduce and BigDecimal::add

  • A+

I can understand why Total1 is calculated, but as Total2 is calculated I have no idea! How can a BigDecimal::add be used in a BiFunction? Signatures are not the same !!!

package br.com.jorge.java8.streams.bigdecimal;  import java.math.BigDecimal; import java.util.ArrayList; import java.util.List;  public class BigDecimalSumTest {     public static void main(String[] args) {          List<BigDecimal> list = new ArrayList<>();          list.add(new BigDecimal("1"));         list.add(new BigDecimal("2"));          BigDecimal total1 = list.stream().reduce(BigDecimal.ZERO, (t, v) -> t.add(v));          BigDecimal total2 = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);          System.out.println("Total 1: " + total1);         System.out.println("Total 2: " + total2);     } } 


Given BigDecimal::add is being used as a BiFunction<BigDecimal, BigDecimal, BigDecimal>, the compiler will look for one of two eligible signatures.

The first possible signature, as you have picked up on, would be a two-argument static method. The relevant lambda would be (a, b) -> BigDecimal.add(a, b). Of course, you are correct to recognise that this doesn't exist.

The second possible signature would be a one-argument instance method. The equivalent lambda here would be (a, b) -> a.add(b). As this one exists and the other does not, this is how the compiler would interpret it.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: