I've been wondering whether transparent implicit
conversions are really such a good idea and whether it might actually be better to use implicits more, um, explicitly. For example, suppose I have a method which accepts a Date
as a parameter and I have an implicit conversion which turns a String
into a Date
:
implicit def str2date(s: String) : Date = new SimpleDateFormat("yyyyMMdd").parse(s)
private def foo(d: Date)
Then obviously I can call this with a transparent implicit
conversion:
foo("20090910")
Would it be better to make the fact that I am converting the string into a date more explicit?
class DateString(val s: String) {
def toDate : Date = new SimpleDateFormat("yyyyMMdd").parse(s)
}
implicit def str2datestr(s: String) : DateString = new DateString(s)
So then the usage looks more like:
foo("20090910".toDate)
The advantage of this is that it is clearer later on what is happening - I've been caught out a few times now by transparent implicit
conversions I should know about (Option
to Iterable
anyone?) and this usage still allows us to take advantage of the power of implicit
s.