Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala : reassignment to val [duplicate]

Tags:

scala

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)
like image 603
user1993412 Avatar asked Jun 17 '14 15:06

user1993412


People also ask

How to reassign a val in Scala?

In Scala, reassignment to val is not allowed, but we can create a new val and assign the value to it. We can see an error when reassigning the values to a val . As a workaround, we can assign the result to a new val and use it.

Can a VAL be changed in Scala?

In short: No, you cannot.

What is difference between Val and VAR in Scala?

The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable.


1 Answers

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)
like image 137
Lee Avatar answered Oct 07 '22 03:10

Lee