2

I am trying to deal with Java8 method references and encountered very strange compile error.

I had a map with object values and I want to provide for user to apply some functions on values.

So I used generic method which takes map key and functional interface as parameter

And I am wondering why I don't need to cast Method reference to precise real type (in case of trim)

import java.util.HashMap;
import java.util.Map;
import java.util.function.UnaryOperator;

public class ReferenceDiscovering {

    Map<String, Object> values = new HashMap<>();

    public static void main(String[] args) {
        ReferenceDiscovering main = new ReferenceDiscovering();
        main.values.put("key1", " some text with space in start");
        main.values.put("key2", "AAAAAAAAAAAAAA");

        System.out.println(main.values);

        main.applyFunctionByKey("key1", String::trim);
        //        cannot resolve method toLowerCase
        //        COMPILE ERROR HERE. WHY???? WHY NOT FOR trim?
        //        main.applyFunctionByKey("key2", String::toLowerCase);
        main.applyFunctionByKey("key2", (UnaryOperator<String>)String::toLowerCase);


        System.out.println(main.values);
    }

    private <T> void applyFunctionByKey(String key, UnaryOperator<T> binaryOperator) {
        if (values.containsKey(key)) {
            values.put(key, binaryOperator.apply((T)values.get(key)));
        }
    }
}

Result:

{key1= some text with space in start, key2=AAAAAAAAAAAAAA} {key1=some text with space in start, key2=aaaaaaaaaaaaaa}

3
  • 5
    You forgot to mention which compile error you got exactly. It could have to do with the fact that toLowerCase has two overloads, but we can't tell without the error. Please edit your question and include that. Commented Aug 25, 2017 at 16:32
  • Added it into code. Seems to strange for me why it could resolve method after casting if there are 2 of them Commented Aug 25, 2017 at 16:36
  • 1
    This compilation error makes it sound like @RealSkeptic's theory about overloads is probably correct: ideone.com/I1Y7Am Commented Aug 25, 2017 at 20:52

1 Answer 1

1

The answer was already given in comments to the question - yes, the problem is that Java cannot decide which method from String class should be used (there are two - one with no-arg and second with Locale).

This is also related to infering of the method type arguments. In the context of provided code JRE cannot do this.

See also:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.