scala在Option类中重新分配给val(scala reassignment to val in Option Class)

我的代码如下所示:

case class SRecord(trialId: String, private var _max:Int) { def max=_max def max_=(value:Int):Unit=_max=value }

之后我将一个函数应用到它上面:

def groupSummaryRecords(it:Iterator[Option[SRecord]], optionSummary:Option[SRecord]):Option[SRecord] = { var max=0; var sRecord1 : Option[SRecord] = None var i=0 while(it.hasNext) { var sRecord:Option[SRecord] = it.next(); if(i==0) { sRecord1 = sRecord; } .. } sRecord1.max=max; // getting 'reassignment to val' compilation error .. }

为什么我得到这个编译错误,以及如何解决它?

如果我将sRecord和sRecord1实例更改为SRecord类型而不是Option[SRecord]以及方法签名,但它仍然可以正常工作。

但是在某些情况下,我可能有一个空SRecord因此使用None/Some 。 我是Scala的新手,如果你问我,使用Option/Some都会感觉真的很痛苦,我只是想删除所有这些Option废话,并在'Java'中测试'null',至少我的代码可以工作??!

My code looks like:

case class SRecord(trialId: String, private var _max:Int) { def max=_max def max_=(value:Int):Unit=_max=value }

Then later on I apply a function onto it:

def groupSummaryRecords(it:Iterator[Option[SRecord]], optionSummary:Option[SRecord]):Option[SRecord] = { var max=0; var sRecord1 : Option[SRecord] = None var i=0 while(it.hasNext) { var sRecord:Option[SRecord] = it.next(); if(i==0) { sRecord1 = sRecord; } .. } sRecord1.max=max; // getting 'reassignment to val' compilation error .. }

Why am i getting this compilation error, and how to fix it ?

If I instead change sRecord and sRecord1 instances to be of type SRecord instead of Option[SRecord] as well as the method signature, it all works fine however.

But in some cases I may have a null SRecord hence the use of None/Some. I am new to Scala, using Option/Some all over feels like a real pain if you ask me, i am just thinking of removing all this Option nonsense and testing for 'null' in good ol' Java, at least my code would work ??!

最满意答案

使用sRecord1.max=max您正试图调用Option[SRecord]上的max方法,而不是SRecord 。 你想访问包含的SRecord (如果有的话)并调用该方法,这可以使用foreach完成:

sRecord1.foreach(_.max=max)

这是为了:

sRecord1.foreach( srec => srec.max=max )

(实际名称为“srec”,编译器将分配一些内部名称,但您明白了)。 如果sRecord1是None ,那么这将不会执行任何操作,但如果它是Some(srec) ,则将传入方法执行以对包含的实例进行操作。

With the line sRecord1.max=max you are trying to call the max method on an Option[SRecord], not an SRecord. You want to access the contained SRecord (if any) and call the method on that, which can be done using foreach:

sRecord1.foreach(_.max=max)

which is desugared to:

sRecord1.foreach( srec => srec.max=max )

(the actual name "srec" is made up, the compiler will assign some internal name, but you get the idea). If sRecord1 is None, this won't do anything, but if it is Some(srec), the method execution will be passed in to operate on the contained instance.

更多推荐