16

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

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)
ZygD
  • 22,092
  • 39
  • 79
  • 102
user1993412
  • 802
  • 2
  • 15
  • 29

1 Answers1

24

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

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)
Lee
  • 142,018
  • 20
  • 234
  • 287