stringscaladatescala-option

Scala how to instantiate new Option[java.sql.Date] type


I have var date_of_birth2 : Option[java.sql.Date] = None.

Later I have to fill date_of_birth2 by string.

 String date = "01/01/1990"
 var formate = new SimpleDateFormat("dd/MM/yyyy").parse(date)
 var aDate = new java.sql.Date(formate.getTime()); 

But aDate is just the type of java.sql.Date. How can I assign?

var mdate_of_birth2 : Option[java.sql.Date] = date // date is just String type


Solution

  • Instead of explicitly using a Some, as suggested by @hezamu, you could use the apply method on the Option companion like so:

    val maybeADate:Option[Date] = Option(aDate)
    

    In this case, in the off chance that aDate was null, then your Option would be a None instead of Some(null) which would be undesirable.