使用Null初始化错误的前向引用

时间:2016-08-26 13:01:27

标签: scala functional-programming

我们经常在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  
} 

但是,我收到了错误的转发参考编译错误。

我猜问题是初始化为null  currentObject?

更新:

这里是实际代码:

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
}

提前致谢。

1 个答案:

答案 0 :(得分:2)

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