Scala:重新分配给val

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24268134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:21:22  来源:igfitidea点击:

Scala : reassignment to val

scala

提问by user1993412

I am looking for a way to resolve the below compilation error in Scala. Where , I am trying to update the value of a variable clinSig , if the clinSig is null while calling method1.

我正在寻找一种方法来解决 Scala 中的以下编译错误。哪里,我试图更新变量 clinSig 的值,如果调用 method1 时 clinSig 为空。

import org.joda.time.Instant 
import java.util.Calendar

class TestingClass {   
    method1(null)   
    private def method1 (clinSig : Instant) {
    if (clinSig == null) {
      val calendar = Calendar.getInstance()
      calendar.set(2011, 0, 5, 0, 0, 0)
      calendar.set(Calendar.MILLISECOND, 0)
      clinSig = new Instant(calendar.getTime)
    }
    print(clinSig)   
   } 
}


error: reassignment to val
 [INFO]       clinSigUpdtDtTm = new Instant(calendar.getTime)

Any inputs would be helpful.

任何输入都会有所帮助。

Thanks !!!

谢谢 !!!

回答by Lee

Method parameters are vals so you can't re-assign them. You can create a new valand assign that based on the condition:

方法参数是vals,因此您不能重新分配它们。您可以创建一个新的val并根据条件分配它:

val updated = if (clinSig == null) {
    val calendar = Calendar.getInstance()
    calendar.set(2011, 0, 5, 0, 0, 0)
    calendar.set(Calendar.MILLISECOND, 0)
    new Instant(calendar.getTime)
}
else clinSig

println(updated)