Casting Problem with Option[String] and String

16 views
Skip to first unread message

Pasturel

unread,
Nov 18, 2011, 11:59:01 AM11/18/11
to scala...@googlegroups.com
The code below throws an exception:

var dateFormat:String=(("""\d{4}/\d\d/\d\d\s+\d\d:\d\d:\d\d""".r)
findFirstIn "2010/05/12 15:41:14;8432.598881355932").asInstanceOf[String]
println ("date format="+dateFormat)
val sdf=new SimpleDateFormat("""yyyy/MM/dd HH:mm:ss""")
val dateLong=sdf.parse(dateFormat).getTime
println ("date format="+dateFormat+" ,dateLong="+dateLong)

it complains when parsing :

scala> var dateFormat:String=(("""\d{4}/\d\d/\d\d\s+\d\d:\d\d:\d\d""".r)
findFir
stIn "2010/05/12 15:41:14;8432.598881355932").toString()
println ("date format="+dateFormat)
val sdf=new SimpleDateFormat("""yyyy/mm/dd hh:mm:ss""")
val dateLong=sdf.parse(dateFormat).getTime
println ("date format="+dateFormat+" ,dateLong="+dateLong)

date format=Some(2010/05/12 15:41:14)
java.text.ParseException: Unparseable date: "Some(2010/05/12 15:41:14)"
at java.text.DateFormat.parse(DateFormat.java:337)
at .<init>(<console>:12)
at .<clinit>(<console>)
at .<init>(<console>:11)
at .<clinit>(<console>)
at $print(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)

at
scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.sca
la:920)
at
scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:4
3)
at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
at java.lang.Thread.run(Thread.java:662)

I don't understand why dateFormat is Some[String] and not a String
Help would be fine

Simon Ochsenreither

unread,
Nov 18, 2011, 12:06:54 PM11/18/11
to scala...@googlegroups.com
Hi,

findFirstIn returns an Option[String], not a String: http://www.scala-lang.org/api/nightly/index.html#scala.util.matching.Regex

Option[String] cannot be cast to String.

If you are sure it always mathes, you can use get Option#get.

Hope this helps.

Bye,

Simon

Pasturel

unread,
Nov 18, 2011, 12:11:32 PM11/18/11
to scala...@googlegroups.com
Le 18/11/2011 17:59, Pasturel a �crit :
The code tested is : ( replacing instanceOf[String] by toString but the
exception is still thrown)

var dateFormat:String=(("""\d{4}/\d\d/\d\d\s+\d\d:\d\d:\d\d""".r)
findFirstIn "2010/05/12 15:41:14;8432.598881355932").toString()

println ("date format="+dateFormat)

Pasturel

unread,
Nov 18, 2011, 12:16:43 PM11/18/11
to scala...@googlegroups.com
Thanks Simon it runs


Bye
Jean-Louis

Reply all
Reply to author
Forward
0 new messages