【问题标题】:Wrong forward reference with Null initialisation使用 Null 初始化的错误前向引用
【发布时间】:2016-08-26 13:01:26
【问题描述】:

在 Java 中我们经常看到如下算法:

MyObject currentObject = null 

for(MyObject oldObject: objects){
    if(currentObject != null) doSomething
    else doSometing
    currentObject = oldObject  
} 

我正在尝试在 Scala 中实现这一点:

var currentObject: MyObject = null
for(oldObject <- objects){
    if(currentObject != null) doSomething
    else doSometing
    currentObject = oldObject  
} 

但是,我收到了 Wrong Forward 参考编译错误。

我想问题在于初始化为 null 当前对象?

更新:

这里是实际代码:

var protCoord:Coordinates     = new Coordinates()
var prevprotCoord:Coordinates = new Coordinates()
var coordMap = mutable.Map[Coordinates, GenomeCoordinates]()
var protein:EnsemblProteinEntry = null
var codingLength = 0

for (gtfEntry <- gtfEntries.toStream) {
  if (gtfEntry.isGene)
    mapping.addGene(new GTFGeneEntry(gtfEntry))
  if(gtfEntry.isTranscript){
    mapping.addTranscriptID(gtfEntry)
  if(protein != null) protein.multiMapCoordinates = coordMap // **I'm receiving the error here** 
    var protein = fastaEntries.getOrElse(gtfEntry.transcriptIdentifier, null)
  if(protein == null)
    protein = new EnsemblProteinEntry()
  protCoord = new Coordinates()
  prevprotCoord = new Coordinates()
  coordMap = mutable.Map[Coordinates, GenomeCoordinates]()
  codingLength = 0
}

提前致谢。

【问题讨论】:

  • 需要更多信息。代码看起来不错。
  • 注意:尽量避免在 Scala 中使用 null - 改用 Option(及其子类型 SomeNone)。见:stackoverflow.com/questions/9698391/when-to-use-option
  • 我怀疑如果你这样做 for{ whatever &lt;- ... } { theVar = whatever } 它会起作用,但会违反所有这些编码。
  • 顺便说一句,Scala fors 需要有一个“右手边”,或者之后的东西,要么是一个直接的表达式(或像 {...} 这样的块),要么后面是 yield 和一个表达式或块。

标签: scala functional-programming


【解决方案1】:

在循环中,您第二次定义了var protein。问题是您在定义之前尝试在循环内使用protein

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多