Ramesh Ramesh - 2 months ago 7
Scala Question

Scala Variables scope

I have created a simple method which is returning a Date value.
Before processing the method "convertStrToDate" i want to do a null check condition. So that if it is not null then i want to process the method.
The problem am facing is that the scope of the variable returnvar is with in the "If loop". So i could not use the variable "returnvar" outside the if loop where i actually need to return as a output to the method.
Can anyone please help to fix this.

def convertStrToDate(inputvar: String): Date = {
if (inputvar != null && inputvar.nonEmpty) {
val format = new java.text.SimpleDateFormat(inputvar)
val formattedvar: Date = format.parse(inputvar)
var returnvar = new java.sql.Date(formattedvar.getTime());
}
return returnvar
}

Answer

You can use Option for this purpose.

If your computation is successful return Some(value) or else return None

Notice that return type of method is changed to Option[Date]

  def convertStrToDate(inputvar: String): Option[Date] = {
      if (inputvar != null && inputvar.nonEmpty) {
        val format = new java.text.SimpleDateFormat(inputvar)
        val formattedvar: Date = format.parse(inputvar)
        var returnvar = new java.sql.Date(formattedvar.getTime())
        Some(returnVar)
      } else None
    }

Note that return is optional in scala

Comments