tesnik03 tesnik03 - 3 months ago 25
Scala Question

implicit conversion Option[T] to String

I am trying to use implicit to convert option value in scala to String but somehow its working. Here is my syntax -

object ToStringParser{
implicit def optionAnyToString[T](input: Option[T]):String = {
input match {
case Some(i) => i.toString
case None => "NULL"
}
}
}


And I am using it like -

import domain.processors.ToStingParser._
println(submitDate)


But this is always printing -

Some(2016-08-02T17:55:03.000-04:00)


How do we have implicit for Options

Answer

Your problem is that println accepts a parameter of type Any, so it has no way to know that you want it to use your implicit conversion, you have to tell it somehow that you want a String, rather than an Option.

This would work: println(submitDate: String), and so would this: def puts(s: String) = println(s); puts(submitDate).

But it really doesn't seem to save you much compared to just doing it explicitly in this case:

println(submitDate.getOrElse("NULL"))

which would be a lot clearer to the reader.

Comments