-2

I am currently trying to get a high order function working, but it keeps telling me that f may not have been defined. My understanding is that it should be defined as it must be given in order to run the method IntApply. Any advice would be appreciated.

package iterators;

import java.util.Iterator;

public class IntApply implements Iterator {

    // The function that will be applied to each input element to make an output element
    private final IntApplyFunction f;

    // The Iterator that this Apply object will get its input from
    private final Iterator<Integer> input;      

    public IntApply(IntApplyFunction f, Iterator<Integer> input) {
        while(input.hasNext()){
            f.apply(input.next());
        }
    }

    @Override
    public boolean hasNext() {
        return input.hasNext();
    }

    @Override
    public Integer next() {
        return input.next();
    }

}
Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34
Dan
  • 1
  • 2

1 Answers1

-1

You have declared f and input as final you either have to initialize them in your constructor/constructors or remove the final keyword.

In this particular case, since your receiving the variable as an argument you can assign it to the object variable field.

public IntApply(IntApplyFunction f, Iterator<Integer> input) {
    this.f = f;
    this.input = input;
    // rest of the constructor
}

Here you can see what is the final keyword. How does the "final" keyword in Java work? (I can still modify an object.)

Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34
  • I tried removing the final and still have the same error. Also I tried including the statement this.f = f; in the constructor but that didn't fix it either. Thank you for the advice though. – Dan Mar 11 '18 at 03:51
  • What type is f in "private final IntApplyFunction f;" What is IntApplyFunction? – Zebrafish Mar 11 '18 at 03:55
  • From my understanding it is a higher order function, which is to say an unspecified function that can be used by iterators change the data based off what function is passed into it. – Dan Mar 11 '18 at 04:02
  • Well no matter what type f is, initializing `this.f` and `this.input` should solve the problem. Removing final is the other solution. I edited the answer because I missed in the first place the variable `input`. – Jose Da Silva Gomes Mar 11 '18 at 04:04
  • I got it working. I didn't actually have to remove the final, I just needed the two constructors. Thank you for the help. – Dan Mar 11 '18 at 04:34
  • Yep, here's what I have working. public IntApply(IntApplyFunction f, Iterator input) { this.f = f; this.input = input; while(input.hasNext()){ f.apply(input.next()); } } – Dan Mar 11 '18 at 04:40
  • Yeap, it was either that or removing the final, not both. – Jose Da Silva Gomes Mar 11 '18 at 04:45