Home > Back-end >  How can I use Java 11 repeat() method in a Method reference?
How can I use Java 11 repeat() method in a Method reference?

Time:04-23

public class X{
    public static void print(Integer n, Function<Integer, String> fn) {
        System.out.println(fn.apply(n));
    }

     public static void main(String []args){
        print(3, Integer::repeat()); //
     }
}

Example:

Since 3 is a given number, the value returned by the function and printed on the console should be "aaa".

CodePudding user response:

Your method reference is wrong in a couple ways. First, a method reference doesn't end in parentheses (). Second, the Integer class doesn't have any repeat method.

The String class defines the repeat method, available for the first time in Java 11. But you want to execute on a specific instance of a string, namely the constant "a".

Try "a"::repeat.

CodePudding user response:

Method references as well as lambda expressions should conform to a function interface, by providing an implementation of the abstract method defined by this interface.

And interface Function declares a method apply()

R apply(T t);

You can implement it like that with lambda expression:

Function<Integer, String> fun = num -> String.valueOf(num);

Method repeat() is an instance method of the String class, i.e. you have to invoke it on the instance of the String. So, need to define this string either by outside the lambda or hard-code it inside the body of lambda.

public static final String str = "a";

Function<Integer, String> fun = num -> str.repeat(num);

Now, in order to transform this lambda expression in a method reference, let's first pose the question of what the method reference is.

Method reference - is the way to utilize an existing method to provide an implantation of the behavior defined by a function interface.

There are four kinds of method references (a quote from the Oracles's tutorial):

  • Reference to a static method ContainingClass::staticMethodName
  • Reference to an instance method of a particular object containingObject::instanceMethodName
  • Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName
  • Reference to a constructor ClassName::new

Note that the syntax of method references doesn't require parentheses () because that how the language was designed, and I guess because method references are intended to be concise and expressive.

The type of method reference that we need to implement this function using repeat() method is a reference to an instance method of a particular object (because repeat() is an instance method). And that's how it might look like:

public static final String str = "a";

Function<Integer, String> fun = str::repeat;

print(3, fun); // or print(3, str::repeat);

Note that variables used inside both method references and lambda expressions must be final or effectively final, i.e. should be assigned only once.

  • Related