【问题标题】:uncompilable source code - variable might not have been initialized无法编译的源代码 - 变量可能尚未初始化
【发布时间】:2018-03-11 03:37:07
【问题描述】:

我目前正在尝试让高阶函数工作,但它一直告诉我 f 可能尚未定义。我的理解是它应该被定义为必须给出它才能运行 IntApply 方法。任何建议将不胜感激。

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();
    }

}

【问题讨论】:

  • 发布您的代码而不是图片
  • 只是提示,如果您将代码发布为图片,这里的人会将您钉死在十字架上。人们希望能够复制和粘贴代码以自己进行测试。
  • 我很抱歉,进行了更改

标签: java higher-order-functions


【解决方案1】:

您已将 finput 声明为 final 您必须在构造函数中初始化它们或删除 final 关键字。

在这种特殊情况下,由于您将变量作为参数接收,因此您可以将其分配给对象变量字段。

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

在这里您可以看到final 关键字是什么。 How does the "final" keyword in Java work? (I can still modify an object.)

【讨论】:

  • 我尝试删除final,但仍然有同样的错误。我也尝试包括声明 this.f = f;在构造函数中,但这也没有解决它。不过还是谢谢你的建议。
  • “private final IntApplyFunction f;”中的f是什么类型什么是 IntApplyFunction?
  • 据我了解,它是一个高阶函数,也就是说迭代器可以使用的未指定函数根据传递给它的函数来更改数据。
  • 好吧,不管 f 是什么类型,初始化 this.fthis.input 应该可以解决问题。删除 final 是另一种解决方案。我编辑了答案,因为我首先错过了变量input
  • 我搞定了。我实际上不必删除 final,我只需要两个构造函数。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 2012-03-25
  • 2015-07-04
  • 1970-01-01
相关资源
最近更新 更多