更新时间:2022-10-17 10:32:16
I believe that the more "explicit" way of doing implicit conversions is much better in terms of readability than the fully transparent one, at least in this example.
In my opinion, using implicit
s fully transparently from type A
to type B
is OK when you can always view an object of type A
as being able to be used whenever and object of type B
is needed. For example, the implicit conversion of a String
to a RandomAccessSeq[Char]
always makes sense - a String
can always, conceptually, be viewed as a sequence of characters (in C, a string is just a sequence of characters, for example). A call to x.foreach(println)
makes sense for all String
s.
On the other hand, the more explicit conversions should be used when an object of type A
can sometimes be used as an object of type B
. In your example, a call to foo("bar")
does not makes sense and throws an error. As Scala does not have checked exceptions, a call to foo(s.toDate)
clearly signals that there might be an exception thrown (s
might not be a valid date). Also, foo("bar".toDate)
clearly looks wrong, while you need to consult documentation to see why foo("bar")
might be wrong. An example of this in the Scala standard library is conversions from String
s to Int
s, via the toInt
method of the RichString
wrapper (String
s can be seen as Int
s, but not all the time).