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)
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.
In short: No, you cannot.
The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable.
Method parameters are val
s 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With