简体   繁体   中英

Cannot convert from java.lang.Integer to R

I have the following code:

class inner {
    Integer i;
    public Integer getValue() {
        return i;
    }
    public void setValue(Integer i) {
        this.i = i;
    }
}

class outer {
    public static inner i1;

    outer(Integer i) {
        i1.setValue(i);
    }
}

public class MyClass{
public void main() {
    List<Integer> ll = Arrays.asList(new outer(2)).stream().map(outer.i1::getValue).collect(Collectors.toList());

}

I get the following error:

required: Function<? super Object,? extends R>
  found: outer.i1::getValue
  reason: cannot infer type-variable(s) R
    (argument mismatch; invalid method reference
      method getValue in class inner cannot be applied to given types
        required: no arguments
        found: Object
        reason: actual and formal argument lists differ in length)
  where R,T are type-variables:
    R extends Object declared in method <R>map(Function<? super T,? extends R>)

I am new to streams, and reading the docs doesn't clear this up for me. Any help will be appreciated.

getValue is a method that takes no arguments. When you try to pass a method reference of getValue to Stream 's map method, you are trying to pass the Stream 's element to getValue , but getValue doesn't take any arguments.

You can replace the method reference with a lambda expression if you wish to ignore the outer element of the Stream:

List<Integer> ll = Arrays.asList(new outer(2)).stream().map(o -> outer.i1.getValue()).collect(Collectors.toList());

However, this will lead to a NullPointerException , since you don't initialize public static inner i1 anywhere, so invoking the outer constructor will throw that exception.

It's hard to suggest how to fix that without knowing what you are trying to do.

I don't know if it makes sense to have a static member of type inner in your outer class, but if it makes sense, you should probably initialize it in a static initializer block (or in its declaration).

You could, for example, change

public static inner i1;

to

public static inner i1 = new inner();

which will eliminate the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM