Ramesh
Ramesh

Reputation: 1593

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
}

Upvotes: 1

Views: 385

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

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

The idiomatic way.

Get Some(input) if inputvar is valid and then map to produce subsequent values.

def convertStrToDate(inputvar: String): Option[Date] = { 
   Option(inputvar).filter(_.nonEmpty).map { inputStr =>
     val format = new java.text.SimpleDateFormat(inputStr)
     val formattedvar: Date = format.parse(inputStr)
     new java.sql.Date(formattedvar.getTime())      
   }
}

Upvotes: 3

Related Questions