0

Quite often in Java we see algorithms like:

MyObject currentObject = null 

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

I'm trying to implement this in Scala:

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

However, I'm receiving a Wrong Forward reference compilation error.

I guess the problems is with the initialisation as null of the currentObject?

UPDATED:

Here the actual code:

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
}

Thanks in advance.

Alec
  • 31,829
  • 7
  • 67
  • 114
ypriverol
  • 585
  • 2
  • 8
  • 28
  • Need more info. Code looks fine. – Nagarjuna Pamu Aug 26 '16 at 13:11
  • Note: Try to avoid using `null` in Scala - use `Option` (with its subtypes `Some` and `None`) instead. See: http://stackoverflow.com/questions/9698391/when-to-use-option – Jesper Aug 26 '16 at 13:21
  • I suspect that if you do `for{ whatever <- ... } { theVar = whatever }` it will work, but against all this encoding. – pedrofurla Aug 26 '16 at 17:06
  • Btw, Scala `for`s need to have a "right hand side", or something after then, either a straight expression (or block like `{...}`) or followed by `yield` with a expression or block. – pedrofurla Aug 26 '16 at 17:08

1 Answers1

2

Inside the loop you have var protein defined second time. The problem is that you try to use protein inside loop before it's defined.

Nebril
  • 884
  • 8
  • 17