0

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

dbc
  • 104,963
  • 20
  • 228
  • 340
masiboo
  • 4,537
  • 9
  • 75
  • 136

3 Answers3

5

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.

cmbaxter
  • 35,283
  • 4
  • 86
  • 95
2

Since the parse method will throw an exception if there is a formatting error, you might also consider using Try, to squash failures to None.

val aDate = Try(new SimpleDateFormat("dd/MM/yyyy").parse(date))
    .map(d => new java.sql.Date(d.getTime()))
    .toOption

If you do want it to throw an exception, then I would go with @cmbaxter's answer using Option.apply.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
1

You wrap it in Some:

var mdate_of_birth2: Option[java.sql.Date] = Some(aDate)

You should see if you can refactor your code to make it a val, though.

hezamu
  • 1,534
  • 1
  • 11
  • 15