Odd syntax in API "String :: concat"

I watched some changes made to the Java SE API with 1.8, and I look at the new Map.merge method , it shows an example of how to use it with a line

map.merge(key, msg, String::concat) 

I understand how to use lambda expressions to create anonymous functional interfaces, but this seems to use a method like BiFunction. I like to understand and use obscure Java syntaxes, but I can't find any mention of this anywhere.

+6
source share
1 answer

String::concat is a reference to the concat() method of the String class.

A BiFunction is a functional interface with a single apply method that takes two parameters (the first of types T and the second of type U ) and returns a result of type R (in other words, the BiFunction<T,U,R> interface has a method R apply(T t, U u) ).

map.merge expects a BiFunction<? super V,? super V,? extends V> BiFunction<? super V,? super V,? extends V> BiFunction<? super V,? super V,? extends V> as the third parameter, where V is the value of Map . If you have a Map with a String value, you can use any method that takes two String parameters and returns String .

String::concat satisfies these requirements and why it can be used in map.merge .

The reason he satisfies these requirements requires an explanation:

The signature of String::concat is equal to public String concat(String str) .

This can be considered as a function with two parameters of type String ( this , the instance for which this method is called, and parameter str ) and the result of type String.

+5
source

Source: https://habr.com/ru/post/972426/


All Articles