【发布时间】: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(及其子类型Some和None)。见:stackoverflow.com/questions/9698391/when-to-use-option -
我怀疑如果你这样做
for{ whatever <- ... } { theVar = whatever }它会起作用,但会违反所有这些编码。 -
顺便说一句,Scala
fors 需要有一个“右手边”,或者之后的东西,要么是一个直接的表达式(或像{...}这样的块),要么后面是yield和一个表达式或块。
标签: scala functional-programming